C++ 头文件链接器错误

标签 c++ header linker-errors

我制作了以下由 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/

相关文章:

c++ - 使用带有 std::vector 和特征矩阵的模板时,来自 GCC 的未定义引用错误?

apache - 使用 deflate 在 Apache 中缓存图像、JS 和 CSS

C++ 使用来自另一个标识符下的头文件的包含类

c++ - Unresolved 错误

没有默认构造函数的 C++ 继承

c++ - 存储STL列表迭代器的指针安全吗?

c++ - 使用 boost::asio 查找子网上所有可访问的 ip

c++ - 循环直到输入特定字符 (C++)

javascript - 警告 - 未处理的 promise 拒绝 : Can't set headers after they are sent

c++ - 使用defalt args时,函数_main中引用的错误LNK2019无法解析的外部符号