调用其他文件未定义引用的 header 中的函数

Call to function in header of other file undefined reference

首先,我想说我对 c++ 有点缺乏经验。

我正在为一个使用柔荑花草的大学项目工作。其中我有 3 个文件(与这个问题相关),TestCode.cppRobotInfo.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。

现在每次我尝试 运行 时,我都会收到以下错误:undefined reference to `Joints::size()' ,指向size() 调用 TestCode.cpp.

如果我将 TestCode.cpp 中的 include 更改为 #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 向我指出了这一点。很抱歉在这么简单的问题上浪费你的时间。

您的 .cpp 预计 return:

int Joints::size() {
    return (int) info.size();
}

你的 .h 是 void:

static void size();

你的电话是 void(错误):

Joints::size();

注意:声明一个 Joints 类型的对象,然后对该对象调用 size()(以及任何其他函数)。喜欢:

Joints MyObject;
int size = MyObject.size(); 

问题是我在 CMakeLists 中犯了一个错误,它没有将 RobotInfo.cpp 与 TestCode.cpp 一起编译,所以在调用 RobotInfo.h 时找不到实现并会抛出错误。