[cpp] view plain copy
- #include<iostream>
- #include<thread>
- void hello()
- {
- std::cout<<"hello concurrent world\n";
- }
- int main()
- {
- std::thread t(hello);
- t.join();
- }
我安装了g++-4.8.5版本编译器,支持C++11,使用命令行g++-4.8 -std=c++11 -lpthread *.cpp编译后,得到的可执行文件在运行时遇到错误:
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted\
Aborted (core dumped)
在查了好久才发现问题,是编译器的问题,编译时要加上选项
-Wl,--no-as-needed
因为gcc4.6以后对于ld自动加上了as-needed选项。所以编译选项应该变成:
g++ -Wl,--no-as-needed -std=c++11 -pthread main.cpp
或者
g++ -std=c++11 -o main -Wl,--no-as-needed main.cpp -lpthread
这样就没有问题了!\
如果是使用qtcreator的话,则需要在.pro文件加入:
LIBS += -pthread
QMAKE_CXXFLAGS += -pthread
QMAKE_CXXFLAGS += -std=c++11