簡體   English   中英

嘗試使用Code :: Blocks編譯第二個模塊時出現C ++鏈接器錯誤

[英]C++ linker error when trying to compile a second module using Code::Blocks

因此,我正在嘗試學習C ++,並且我已經使用頭文件了。 他們對我來說真的毫無意義。 我已經嘗試了多種組合,但到目前為止沒有任何效果:

Main.cpp的:

#include "test.h"

int main() {
    testClass Player1;
    return 0;
}

test.h:

#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
class testClass {
    private:
        int health;
    public:
        testClass();
        ~testClass();
        int getHealth();
        void setHealth(int inH);
};
#endif // TEST_H_INCLUDED

TEST.CPP:

#include "test.h"

testClass::testClass() { health = 100; }
testClass::~testClass() {}

int testClass::getHealth() { return(health); }
void testClass::setHealth(int inH) { health = inH; }

我想做的事情很簡單,但是頭文件的工作方式對我完全沒有意義。 代碼塊在構建時返回以下內容:

obj \\ Debug \\ main.o(.text + 0x131)||在函數main':| *voip*\\test\\main.cpp |6|undefined reference to main':| *voip*\\test\\main.cpp |6|undefined reference to testClass :: testClass()'|的main':| *voip*\\test\\main.cpp |6|undefined reference to obj \\ Debug \\ main.o(.text + 0x13c): voip \\ test \\ main.cpp | 7 |未定義對`testClass ::〜testClass()'|的引用 || ===構建完成:2個錯誤,0個警告=== |

我將不勝感激。 或者,如果您有一個不錯的教程,那也很好(我用Google搜索的大多數教程都沒有幫助)

設置標題的方式沒有任何問題。 鏈接時發生錯誤。 您的gcc命令行是什么? 我的猜測是您只編譯main.cpp,而忘記了test.cpp。

Code :: Blocks不知道它必須編譯test.cpp並生成目標文件test.o (以便后者可以與main.o鏈接在一起以生成可執行文件)。 您必須將test.cpp添加到您的項目。

在“代碼::塊”中,轉到菜單中的“ Project>Add File ,然后選擇您的test.cpp文件。 確保同時選中了發布和調試復選框。

然后Build->Rebuild

編輯:

這是一個提示,可幫助您在編譯時了解IDE的功能。 轉到Settings -> Compiler and Debugger -> Global Compiler Settings -> Other settings然后在Compiler logging下拉框中選擇Full command line 現在,無論何時構建,gcc編譯器命令都會記錄在“構建日志”中。 每當StackOverflow上有人要求您使用gcc命令行時,您都可以復制並粘貼構建日志中的內容。

您正在使用什么命令來構建? 似乎您沒有在test.cpp編譯和鏈接,因此當main.cpp去尋找合適的符號時,它找不到它們(鏈接失敗)。

如其他答案所述,這是鏈接錯誤。 像這樣編譯和鏈接:

g++ Main.cpp test.cpp -o myprogram -Wall -Werror

一些有關頭文件的(簡短)信息-.cpp文件中的#include行僅指示編譯器將該文件的內容粘貼到此時要編譯的流中。 因此,它們使您可以在一個位置(test.h)聲明testClass並在許多位置使用它。 (main.cpp,someother.cpp,blah.cpp)。 您的test.cpp包含testClass方法的定義,因此您也需要將其鏈接到最終的可執行文件中。

但是頭文件沒有任何魔術,只是為了方便起見使用簡單的文本替換,因此您不必一遍又一遍地聲明相同的類或函數。 您已經(正確地)在其中包含了#ifndef TEST_H_INCLUDED內容,這樣您就有機會獲得someother.h(其中包括test.h和main.cpp)同時包含了test.h和someother.h,您只會得到testClass聲明的單個副本。

希望這可以幫助!

暫無
暫無

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

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