2

所以我正在尝试学习 C++,而且我已经使用头文件了。它们对我来说真的毫无意义。我已经尝试了很多组合,但到目前为止没有任何效果:

主要.cpp:

#include "test.h"

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

测试.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

测试.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 totestClass::testClass()'| obj\Debug\main.o(.text+0x13c): voip \test\main.cpp|7|未定义对`testClass::~testClass()'的引用| ||=== 构建完成:2 个错误,0 个警告 ===|

我会很感激任何帮助。或者,如果您有一个不错的教程,那也可以(我在 Google 上搜索的大多数教程都没有帮助)

4

5 回答 5

4

Code::Blocks 不知道它必须编译test.cpp并生成一个目标文件test.o(以便后者可以链接在一起main.o以生成可执行文件)。您必须添加test.cpp到您的项目中。

在 Code::Blocks 中,进入Project>Add File菜单并选择您的test.cpp文件。确保选中 Release 和 Debug 复选框。

然后Build->Rebuild

编辑:

这是一个提示,可帮助您了解编译时 IDE 在后台执行的操作。转到Settings -> Compiler and Debugger -> Global Compiler Settings -> Other settingsFull command lineCompiler logging下拉框中选择。现在,无论何时构建,gcc 编译器命令都会记录在构建日志中。每当 StackOverflow 上有人询问您使用的 gcc 命令行时,您可以复制并粘贴构建日志中的内容。

于 2010-06-08T20:18:09.853 回答
3

您设置标题的方式没有任何问题。您的错误在链接期间发生。你的 gcc 命令行是什么?我的猜测是您正在编译 main.cpp,而忘记了 test.cpp。

于 2010-06-08T19:53:45.160 回答
0

您使用什么命令来构建?似乎您没有在 中编译和链接test.cpp,因此在main.cpp寻找适当的符号时,它找不到它们(链接失败)。

于 2010-06-08T19:53:48.203 回答
0

正如其他答案中所说,这是一个链接错误。像这样编译和链接:

g++ Main.cpp test.cpp -o myprogram -Wall -Werror
于 2010-06-08T19:58:26.360 回答
0

还有一些关于头文件的(简要)信息——.cpp 文件中的#include 行只是指示编译器将该文件的内容粘贴到此时要编译的流中。所以他们让你在一个地方(test.h)声明testClass并在很多地方使用它。(main.cpp、someother.cpp、blah.cpp)。您的 test.cpp 包含 testClass 方法的定义,因此您还需要将其链接到最终的可执行文件中。

但是头文件并没有什么神奇之处,它只是为了方便而使用的简单文本替换,这样您就不必一遍又一遍地声明相同的类或函数。你已经(正确地)得到了#ifndef TEST_H_INCLUDED 的东西,所以如果你有 someother.h 其中 #includes test.h 和 main.cpp #includes test.h 和 someother.h,你只会得到testClass 声明的一个副本。

希望这可以帮助!

于 2010-06-08T20:05:06.007 回答