1. 程式人生 > >關於在ubuntu下eclipse中c++11支援和編譯執行c++11報錯的解決方法

關於在ubuntu下eclipse中c++11支援和編譯執行c++11報錯的解決方法

最近準備升級專案中的c++執行緒部分程式碼用c++11簡單重構一下,結果測試demo直接就報錯~

百度和谷歌了一部分還是沒有解決這個問題~

最後經過研究eclipse的自動編譯~終於搞定了~

首先按照網上說的~ http://hkllzh.iteye.com/blog/1620352 配置eclipse的編譯引數,我的平臺是ubuntu14 64位 3.11.0-26-generic

編譯通過了,執行報錯:

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 -pthread
C/C++ Build --> Settings --> Tool Settings --> GCC C++ Compiler --> Miscellanous中新增這個編譯引數

然後發現還是不行-_-#

後來根據eclipse輸出

make all
Building file: ../src/TestC11.cpp
Invoking: GCC C++ Compiler
g++ -D__GXX_EXPERIMENTAL_CXX0X__ -O0 -g3 -Wall -c -fmessage-length=0 -pthread -std=c++0x  -Wl,--no-as-needed -MMD -MP -MF"src/TestC11.d" -MT"src/TestC11.d" -o "src/TestC11.o" "../src/TestC11.cpp"
Finished building: ../src/TestC11.cpp
 
Building target: TestC11
Invoking: GCC C++ Linker
g++  -o "TestC11"  ./src/TestC11.o   
Finished building target: TestC11

發現了問題~eclipse是先編譯成靜態庫然後生成可執行檔案,那麼要在連結階段新增這個引數而不是編譯階段~~~

那麼在C/C++ Build --> Settings --> Tool Settings --> GCC C++ Linker --> Miscellanous 新增,在原先編譯引數的地方刪除

-Wl,--no-as-needed -pthread

再次clean - build - run 執行成功~

=================================================   別高興的太早  =================================================

回到eclipse一看~誒~編譯執行時通過了~但是程式碼中還是報錯~thread類找不到,並且自動提示也沒有,那還敲什麼程式碼~~~

進入標頭檔案<thread>檢視發現thread宣告有巨集定義,並且

#if __cplusplus < 201103L
# include <bits/c++0x_warning.h>
#else
...
#endif
並且
__cplusplus 199711L

恩~上面新增的c++11支援並沒有在程式碼檢查中生效~

最後查到設定在

Workspace settings

Window-> Preference -> Build -> Settings -> Discovery -> CDT GCC Built-in Compiler Settings(shared) 中的
(command to get compiler specs) 改為 ${COMMAND} -E -P -v -dD ${INPUTS} -std=c++11
最後還要重新新建工程~重新整理或者改工程中的
CDT GCC Built-in Compiler Settings(shared)
引數也是不行的~必須新建一個~