C++头文件链接器错误
C++ header file linker error
我制作了以下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让您知道它正在编译,即
错误。。。
显然它没有被编译和链接...
- Netbeans 10:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- CMake 错误:链接器命令失败,退出代码为 1 和 cpp.o 文件
- clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) - 体系结构的未定义符号 x86_64:
- 如何修复 clang: 错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- Android NDK.Build命令失败.未定义的引用.clang++:错误:链接器命令失败,退出代码为1
- 使用cmake错误链接boost日志
- 错误:链接器命令失败,退出代码为 1(使用 -v 查看调用):在 Macbook 上
- C++ XCODE ld:找不到体系结构x86_64 clang 的符号:错误:链接器命令失败,退出代码为 1(使用 -
- clang:错误:链接器命令失败,C++代码中的退出代码为 1(使用 -v 查看调用)
- 静态库中的 g++ 错误链接函数
- 未定义的参考错误链接天然函数Android
- C++编译错误:ld:找不到体系结构x86_64 clang 的符号:错误:链接器命令失败,退出代码为 1(使用 -v
- QT Q_PROPERTY错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- ld:找不到体系结构x86_64 clang 的符号:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- OSX MOJAVE -LD:架构X86_64 clang找不到符号:错误:链接器命令失败,出口代码1
- C 错误链接器命令失败了出口代码1(使用-V查看调用)
- LD:架构x86_64 clang找不到符号:错误:链接器命令失败,出口代码1(使用-v to See
- 聚输出错误 - 链接列表
- Xcode链接器错误:链接器命令失败,退出代码为1(使用-v查看调用)
- 尝试构建C DLIB示例无法与数百个未定义的参考错误链接