C++头文件链接器错误

C++ header file linker error

本文关键字:错误 链接 文件 C++      更新时间:2023-10-16

我制作了以下C++程序,该程序由3个文件组成:

事物.h 文件

    #ifndef THING_H
#define THING_H
class thing{
  double something;
  public:
         thing(double);
         ~thing();
         double getthing();
         void setthing(double);  
         void print();  
};
#endif

东西.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;    
}

以前在一个文件中制作了这个程序,它运行得很好,但是当我尝试将其拆分为单独的文件以创建标头时,我收到链接器错误,这是我尝试从主文件运行它时遇到的错误:

  [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()和朋友)。

解决方案是在创建实际的程序二进制文件时将所有文件链接在一起。 使用 g++ 前端时,可以通过在命令行上一起指定所有源文件来执行此操作。 例如:

g++ -o main thing.cpp main.cpp

将创建名为"main"的主程序。

看来你没有把东西.cpp链接到你的"项目"中。

如果您使用 gcc 进行编译:

g++ thing.cpp -o thing.o
g++ main.cpp -o main.o
g++ main.o thing.o -o my-best-application-ever

如何将文件添加到项目中取决于您使用的编译器/IDE/构建系统。

@sheu是对的。但是,如果您只是在主要内容中包含事物.cpp则无需执行任何操作.cpp由于您已经在 thing 中包含 thing.h .cpp因此如果您包含 thing,一切都会正常工作.cpp

编译器

知道函数的声明,但不知道定义。你需要说出他们在哪里。最简单的方法是创建"项目"并将所有文件添加到其中。然后编译器知道在哪里搜索所有文件。

在东西中放入一些代码.cpp让您知道它正在编译,即

错误。。。

显然它没有被编译和链接...

相关文章: