Linux程序设计 makefile编译多文件时出现error: ld returned 1 exit status

博客讲述在make时出现链接问题,此前百度该错误常认为是窗口开多,但此次并非如此。指出需检查外部函数标志extern是否遗漏以及文件之间的依赖关系。

之前百度这个错误都说是窗口开多了……

但我是在make的时候出现的问题……

链接时出现问题:检查好外部函数标志extern是否有遗漏和文件之间的依赖关系

### 解决多线程编译出现 `collect2: error: ld returned 1 exit status` 的方法 当遇到 `collect2: error: ld returned 1 exit status` 这类链接错误,通常是因为链接器无法找到所需的库文件。对于 C++ 中的多线程编程,常见的原因是未正确链接 pthread 库。 #### 链接 pthread 库的方法 为了使程序能够成功编译并运行多线程代码,需要确保在编译命令中加入 `-lpthread` 参数来链接 pthread 库[^4]: ```bash g++ -o my_program my_program.cpp -pthread ``` 此命令中的 `-pthread` 标志告诉编译器启用 POSIX 线程支持,并自动处理必要的宏定义和库路径设置。 另外一种方式是在源码中包含 `<pthread.h>` 或者使用 C++11 及以上标准自带的 `<thread>` 头文件,这取决于所使用的 API 形式。如果是基于 C++11 的 `std::thread` 接口,则只需保证编译选项中有 `-std=c++11` 即可。 #### 修改 Makefile 文件 如果项目依赖于 Makefile 构建系统,那么应该确认 Makefile 是否已经包含了正确的链接标志。可以在目标规则的目标部分添加 `-pthread`: ```makefile CXXFLAGS += -std=c++11 -pthread LDFLAGS += -pthread ``` 这样可以确保每次调用 g++ 线程应用程序的例子以及如何对其进行编译: ```cpp #include <iostream> #include <thread> #include <unistd.h> using namespace std; void sayHello() { while (true) { sleep(1); cout << endl << "hello" << endl; } } void sayWorld() { while (true) { sleep(1); cout << endl << "world" << endl; } } int main() { thread threadHello(sayHello); thread threadWorld(sayWorld); // Wait for threads to finish (they won't due to infinite loops, so this is just an example) if(threadHello.joinable()) threadHello.join(); if(threadWorld.joinable()) threadWorld.join(); return 0; } ``` 编译该程序应采用如下命令: ```bash g++ -o multi_thread_example multi_thread_example.cpp -std=c++11 -pthread ``` 通过上述调整,应当能有效解决由于缺少 pthread 支持而导致的 `collect2: error: ld returned 1 exit status` 错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值