g++编译C++11遇到的问题:Enable multithreading to use std::thread: Operation not permitted

392 阅读1分钟

[cpp]  view plain  copy

  1. #include<iostream>  
  2. #include<thread>  
  3. void hello()  
  4. {  
  5.     std::cout<<"hello concurrent world\n";  
  6. }  
  7. int main()  
  8. {  
  9.     std::thread t(hello);  
  10.     t.join();  
  11. }  

我安装了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

参考文章:stackoverflow.com/questions/1…