c++ - 调用其他文件 undefined reference 的 header 中的函数

标签 c++ ros catkin

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

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

它们内部有以下代码:

测试代码.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()',指向 TestCode.cpp 中 size() 调用的行。

如果我将 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 期望返回:

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

你的 .h 是一个 void:

static void size();

你的电话是void(而且是错误的):

Joints::size();

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

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

关于c++ - 调用其他文件 undefined reference 的 header 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43944762/

相关文章:

c++ - ROS 与 QtCreator : autocompletion

python - 中断后 Catkin 构建腐败

c++ - 包括来自不同目录的头文件?

c++ - 转换为 const int

c++ - 如何在没有 free() 或 delete 的情况下返回 char*?

ubuntu - ros旋律未满足的依赖关系

c++ - 构建精简版 Qt 4.6.2 时出现问题

compiler-errors - Cmake目录错误

qt-creator - QtCreator 没有索引包含 catkin 包的文件