Linux c++编译总结,持续更新

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没有模板