我制作了以下由 3 个文件组成的 C++ 程序:
thing.h 文件
#ifndef THING_H
#define THING_H
class thing{
double something;
public:
thing(double);
~thing();
double getthing();
void setthing(double);
void print();
};
#endif
thing.cpp 文件
#include <iostream>
#include "thing.h"
thing::thing(double d){
something=d;
}
thing::~thing(){
std::cout << "Destructed" << std::endl;
}
double thing::getthing(){
return something;
}
void thing::setthing(double d){
something = d;
}
void thing::print(){
std::cout <<"The someting is " << something << std::endl;
}
主文件
#include <iostream>
#include "thing.h"
int main(){
thing t1(5.5);
t1.print();
t1.setthing(7.);
double d=t1.getthing();
std::cout << d << std::endl;
system("pause");
return 0;
}
我之前将这个程序全部放在一个文件中并且运行完美,但是当我尝试将它拆分成单独的文件以创建 header 时,我收到链接器错误,这是我尝试从主文件运行时遇到的错误文件:
[Linker error] undefined reference to `thing::thing(double)'
[Linker error] undefined reference to `thing::print()'
[Linker error] undefined reference to `thing::setthing(double)'
[Linker error] undefined reference to `thing::getthing()'
[Linker error] undefined reference to `thing::~thing()'
[Linker error] undefined reference to `thing::~thing()'
ld returned 1 exit status
从上面的错误来看,主文件似乎无法识别标题中的函数,请问我该如何解决?
最佳答案
用稍微不那么迂腐的术语来说:
您的头文件 thing.h
声明“class thing
应该是什么样子”,但没有声明它的实现,它在源文件 thing.cpp 中
。通过在你的主文件中包含头文件(我们称之为 main.cpp
),编译器在编译文件时会被告知 class thing
的描述,但不会class thing
是如何工作的。当链接器尝试创建整个程序时,它会提示找不到实现(thing::print()
和 friend )。
解决方案是在创建实际程序二进制文件时将所有文件链接在一起。使用 g++ 前端时,您可以通过在命令行上一起指定所有源文件来执行此操作。例如:
g++ -o main thing.cpp main.cpp
将创建名为“main”的主程序。
关于C++ 头文件链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14547133/