Code::Blocks编译C++项目时触发collect2.exe链接错误求助
解决collect2.exe: ld returned 1 exit status(预编译头链接错误)
嘿,我一眼就看出问题出在哪了——你遇到的这个collect2.exe: error: ld returned 1 exit status错误,根源是GCC生成的预编译头文件Date.h.gch被错误地当成了可链接的目标文件传给了链接器,所以才会报Date.h.gch: file not recognized: File format not recognized。
为什么会出现这个问题?
*.gch是GCC的预编译头缓存文件,用来加快后续编译速度,但它本身不是编译生成的.o目标文件,不能被链接器处理。你的Code::Blocks项目可能误把这个缓存文件加入了链接步骤的文件列表里,才导致链接器报错。
解决步骤:
- 删除预编译头缓存文件:找到你项目目录里的
Date.h.gch文件,直接删除它。这个文件是自动生成的,删除后不会影响代码,后续编译会根据需要重新生成。 - 检查Code::Blocks项目配置:
- 右键你的项目 →
Build options→ 切换到Compiler settings标签页,看看有没有启用Precompile headers选项。如果启用了,确保只添加了Date.h作为预编译头,不要把.gch文件加进去。 - 切换到项目的
Files标签,检查是不是不小心把Date.h.gch添加成了项目文件,如果是的话,右键它选择Remove from project。
- 右键你的项目 →
- 清理并重新编译项目:点击Code::Blocks顶部菜单栏的
Build→Clean,清理已生成的编译文件,然后再点击Build→Build and run重新编译运行。
验证你的代码
顺便看了下你的代码,本身没有语法错误,不过提个小细节:Main.cpp里的using namespace std;其实没必要,因为你的代码里没用到标准库的内容,不过这不是导致错误的原因,为了规范可以删掉它。
整理后的代码如下:
Date.h
#define DATE_H class Date { private: int m_year; int m_month; int m_day; public: Date(int year, int month, int day); void SetDate(int year, int month, int day); int getYear() { return m_year; } int getMonth() { return m_month; } int getDay() { return m_day; } }; #endif
Date.cpp
#include "Date.h" // Date constructor Date::Date(int year, int month, int day) { SetDate(year, month, day); } // Date member function void Date::SetDate(int year, int month, int day) { m_month = month; m_day = day; m_year = year; }
Main.cpp
#include "Date.h" int main() { Date test(2000, 05, 10); return 0; }
内容的提问来源于stack exchange,提问作者Andres Oropeza
相关产品推荐
相关产品推荐

