【发布时间】:2014-10-31 11:25:06
【问题描述】:
首先,我已经检查了不同的解决方案:
Compile multithreading with gcc
我的环境:
Ubuntu 1404 64 位
gcc 4.8.2
面向 C/C++ 开发人员的 Eclipse IDE
版本:Luna Service Release 1 (4.4.1) 内部版本号:20140925-1800
按照这些链接,我设法编译并运行了一个基本线程程序(代码取自 SO 中的一个链接,但无法再次找到它。如果有人看到它,请编辑我的问题以添加参考)。
#include <iostream>
#include <thread>
#include <vector>
void func(int tid)
{
std::cout << "Launched by thread " << tid << std::endl;
}
int main()
{
std::vector<std::thread> th;
int nr_threads = 10;
for(int i = 0; i < nr_threads; ++i)
{
th.push_back(std::thread(func, i));
}
for(auto &t : th)
{
t.join();
}
return 0;
}
我用来编译它的命令如下(THIS WORKS并且输出文件是可执行的):
g++ --std=c++11 -pthread test.cpp -o test.out
Launched by thread 1
Launched by thread 5
Launched by thread 3
Launched by thread 6
Launched by thread 4
Launched by thread 0
Launched by thread 7
Launched by thread 8
Launched by thread 9
Launched by thread 2
问题是当我尝试设置我的 eclipse 项目时。我可以编译,但它不能产生有效的可运行输出。
编译日志:
12:09:45 **** Incremental Build of configuration Debug for project test ****
make all
Building file: ../test.cpp
Invoking: GCC C++ Compiler
g++ --std=c++11 -pthread -D__cplusplus=201103L -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"test.d" -MT"test.d" -o "test.o" "../test.cpp"
Finished building: ../test.cpp
Building target: test
Invoking: GCC C++ Linker
g++ -o "test" ./test.o
Finished building target: test
12:09:46 Build Finished (took 780ms)
我正在更改构建器、方言的不同设置......正如他们在链接中所说的那样,试图获得我可以用来从终端编译的相同命令。但是没有办法从 eclipse 创建一个有效的输出文件。它总是显示这个错误:
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
知道如何设置eclipse吗?
更新: 按照@Dirk 的指示,我在虚拟机中进行了测试,只需将 pthread 添加到链接器库即可。
但对于我的初始设置,它仍然失败。在将 C/C++ 构建设置 G++ 链接器命令修改为 g++ --std=c++0x -pthread 后,我让它工作了。
所以,很明显我的第一个环境缺少一些东西。
【问题讨论】:
-
如何在工作示例中执行链接?看起来 eclipse 配置为使用 -pthread 进行编译但不用于链接。
-
我没有更改 g++ 链接器设置中的任何内容。当我添加标志 -pthread 时,它会在构建时抛出
make: *** No rule to make target -pthread', needed by test'. Stop. -
只需在链接器设置的库选项下添加pthread即可。
-
我添加了它,现在链接器输出不同 g++ -o "test" ./test.o -lpthread` 但运行时仍然出现同样的错误
-
嗯...你的输出是什么?您评论中的`不是来自复制/粘贴?
标签: c++ eclipse multithreading c++11