首先,我想说我对 c++ 有点缺乏经验。
我正在使用 catkin 为大学做一个项目。其中我有 3 个文件(与这个问题相关),TestCode.cpp,RobotInfo.cpp和RobotInfo.h。
他们里面有以下代码:
TestCode.cpp
#include "RobotInfo.h"
int main(int argc, char **argv) {
....
Joints::size(); //first time any call goes to Joints
...
}
RobotInfo.h
class Joints{
protected:
static map<string, double> info;
public:
static int size();
}
RobotInfo.cpp
#include "RobotInfo.h"
map<string, double > Joints::info = map<string, double>();
int Joints::size() {
return (int) info.size();
}
此外,它们都已添加到 CMakeLists.txt 中。
现在,每次我尝试运行它时,我都会收到以下错误:未定义对 `Joints::size()' 的引用,指向 TestCode.cpp 中 size() 调用的行。
如果我将 TestCode.cpp 中的包含更改为 #include"RobotInfo.cpp" 一切正常,但对我来说,这看起来像是一个肮脏的解决方案。
所以我想知道是什么导致了这个问题,我已经尝试解决这个问题几个小时,但似乎我缺乏经验真的在这个问题上伤害了我。
这也是我构建控制台时控制台输出的所有内容:
/home/manuel/clion-2017.1.1/bin/cmake/bin/cmake --build /home/manuel/catkin_ws/src/cmake-build-debug --target testCode -- -j 4
Scanning dependencies of target testCode
[ 50%] Building CXX object team1/CMakeFiles/testCode.dir/src/TestCode.cpp.o
[100%] Linking CXX executable ../devel/lib/team1/testCode
CMakeFiles/testCode.dir/src/TestCode.cpp.o: In function `main':
/home/manuel/catkin_ws/src/team1/src/TestCode.cpp:32: undefined reference to `Joints::size()'
collect2: error: ld returned 1 exit status
team1/CMakeFiles/testCode.dir/build.make:113: recipe for target 'devel/lib/team1/testCode' failed
make[3]: *** [devel/lib/team1/testCode] Error 1
CMakeFiles/Makefile2:784: recipe for target 'team1/CMakeFiles/testCode.dir/all' failed
make[2]: *** [team1/CMakeFiles/testCode.dir/all] Error 2
CMakeFiles/Makefile2:796: recipe for target 'team1/CMakeFiles/testCode.dir/rule' failed
make[1]: *** [team1/CMakeFiles/testCode.dir/rule] Error 2
Makefile:446: recipe for target 'testCode' failed
make: *** [testCode] Error 2
编辑:
我想通了,这对我来说是一个愚蠢的错误,我在 CMakeLists 上犯了一个错误,它没有将两个文件一起编译,特别感谢@NathaOliver 向我指出了这一点。很抱歉在这么简单的问题上浪费了您的时间。