C++;头文件链接器错误 我已经制作了以下的C++程序,它由3个文件组成:

C++;头文件链接器错误 我已经制作了以下的C++程序,它由3个文件组成:,c++,header,linker-errors,C++,Header,Linker Errors,thing.h文件 #ifndef THING_H #define THING_H class thing{ double something; public: thing(double); ~thing(); double getthing(); void setthing(double); void print(); }; #endif #include <ios

thing.h文件

    #ifndef THING_H
#define THING_H

class thing{
  double something;
  public:
         thing(double);
         ~thing();
         double getthing();
         void setthing(double);  
         void print();  
};

#endif
  #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;    
}
thing.cpp文件

    #ifndef THING_H
#define THING_H

class thing{
  double something;
  public:
         thing(double);
         ~thing();
         double getthing();
         void setthing(double);  
         void print();  
};

#endif
  #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;    
}

从上面的错误看来,虽然主文件无法识别标题中的函数,但我如何解决此问题?

您似乎没有将thing.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/生成系统。

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

用稍微不那么迂腐的术语:

头文件
thing.h
声明了“类thing应该是什么样子”,但没有声明它的实现,它位于源文件
thing.cpp
中。通过在主文件中包含头文件(我们称之为
main.cpp
),编译器在编译文件时会被告知
class thing
的描述,而不是
class thing
的实际工作方式。当链接器尝试创建整个程序时,它会抱怨无法找到实现(
thing::print()
和friends)

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

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

将创建名为“main”的主程序。

@sheu是对的。。但如果只在main.cpp中包含thing.cpp,则无需执行任何操作
既然您已经在thing.cpp中包含thing.h,那么如果您在thing.cpp中包含thing.cpp,那么一切都将正常工作。在thing.cpp中放入一些代码,让您知道它正在编译,即

错误。。。
显然它没有被编译和链接…

看起来你没有链接
东西
编译的代码。解决方案取决于您的构建系统。生成文件是什么样子的?您是如何编译的?你能把commands/makefile放进去吗