簡體   English   中英

在其他文件未定義引用的標頭中調用函數

[英]Call to function in header of other file undefined reference

首先,我想說我對c ++缺乏經驗。

我正在為一個使用柳絮的大學項目。 在其中,我有3個文件(與該問題相關),分別是TestCode.cppRobotInfo.cppRobotInfo.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更改為#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中犯了一個錯誤,它沒有與TestCode.cpp一起編譯RobotInfo.cpp,因此在調用RobotInfo.h時找不到實現,並會拋出錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM