1. 沒有定義的符號
這類的錯誤, 解決辦法:A. 添加對應的頭文件(源文件), B.前置聲明
- 1.1 錯誤描述:
error: variable has incomplete type 'class XXX '
error: 'helper' is not a class, namespace, or enumeration
- 1.2 編譯器說的很清楚,沒有找到其定義, 看看錯誤的代碼
class _utils_api_ helper
{
public:
};
- 1.3 錯誤提示:
[ 20%] Building CXX object CMakeFiles/calc.dir/src/utils.cpp.o
In file included from /home/xxx/demo/call_clang/src/utils.cpp:1:
/home/xx/demo/call_clang/include/utils.h:53:2: error: expected expression
public:
/home/cube/demo/call_clang/include/utils.h:51:20: error: variable has incomplete type 'class _utils_api_'
class _utils_api_ helper
^
/home/xx/demo/call_clang/include/utils.h:51:8: note: forward declaration of 'utils::_utils_api_'
class _utils_api_ helper
^
/home/xx/demo/call_clang/src/utils.cpp:14:14: error: 'helper' is not a class, namespace, or enumeration
std::string helper::wstr2str(const std::wstring& wstr)
- 1.4 分析,這里提示,沒有定義
_utils_api_
, 而用_utils_api_
修飾了類helper - 1.5 解決: 增加對
_utils_api_
的定義。 - 1.6 擴展, 可能沒有包含頭文件就已經在使用頭文件中的函數或者類型,也會出現這樣的錯誤,解決: 增加頭對應的類型引用
2. C++特有的與C一起編譯
- 2.1 錯誤:
In file included from /home/xxx/demo/call_clang/src/utils.cpp:1:
/home/xxx/demo/call_clang/include/utils.h:149:3: error: templates must have C++ linkage
template<typename T>
^~~~~~~~~~~~~~~~~~~~
/home/xxxxxx/demo/call_clang/include/utils.h:42:2: note: extern "C" language linkage specification begins here
extern "C" {
^
/home/xxxxxx/demo/call_clang/include/utils.h:167:3: error: templates must have C++ linkage
template<typename T>
^~~~~~~~~~~~~~~~~~~~
/home/xxxxxx/demo/call_clang/include/utils.h:42:2: note: extern "C" language linkage specification begins here
extern "C" {
重要的是這句提示
error: templates must have C++ linkage
- 2.2 提示說: 模板是C++ 才有的,而我的代碼是:
#ifdef __cplusplus
extern "C" {
#endif //! __cplusplus
class helper
{
public:
template<T>
std::string to_str(T & val)
{
return std::to_string(val);
}
};
#ifdef __cplusplus
}
#endif //! __cplusplus
代碼中使用模板, 又使用extern "C"嘗試兼容C語言,當然不行,C沒有模板