歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Ubuntu 12.04 GCC4.7啟用C++11

Ubuntu 12.04 GCC4.7啟用C++11

日期:2017/2/28 15:49:17   编辑:Linux教程

因為想用template aliases特性,必須要GCC4.7.

又不想編譯源代碼,所以按照下面的方法安裝。

  1. sudo add-apt-repository ppa:Ubuntu-toolchain-r/test
  2. sudo apt-get update
  3. sudo apt-get install gcc-4.7
  4. sudo apt-get install g++-4.7

如果Ubuntu 12.04 系統中存在多個版本的GCC,可以在CMake工程的頂層的CMakeLists.txt中配置:

  1. cmake_minimum_required(VERSION 2.8.7)
  2. set(CMAKE_C_COMPILER "/usr/bin/gcc-4.7")
  3. set(CMAKE_CXX_COMPILER "/usr/bin/g++-4.7")
  4. project (sample)
  5. add_subdirectory(src bin)
然後在build目錄下執行cmake .. 可以看到:
  1. chenshu@chenshu-beijing:~/work/research/tree/normal_tree/build$ cmake ..
  2. -- The C compiler identification is GNU
  3. -- The CXX compiler identification is GNU
  4. -- Check for working C compiler: /usr/bin/gcc-4.7
  5. -- Check for working C compiler: /usr/bin/gcc-4.7 -- works
  6. -- Detecting C compiler ABI info
  7. -- Detecting C compiler ABI info - done
  8. -- Check for working CXX compiler: /usr/bin/g++-4.7
  9. -- Check for working CXX compiler: /usr/bin/g++-4.7 -- works
  10. -- Detecting CXX compiler ABI info
  11. -- Detecting CXX compiler ABI info - done
  12. -- Configuring done
  13. -- Generating done
  14. -- Build files have been written to: /home/chenshu/work/research/tree/normal_tree/build

不過我的方法不是CMake推薦的最佳方法,一共有三種方法可以參考:

http://www.cmake.org/Wiki/CMake_FAQ#Method_3_.28avoid.29:_use_set.28.29

  1. How do I use a different compiler?
  2. [edit] Method 1: use environment variables
  3. For C and C++, set the CC and CXX environment variables. This method is not guaranteed to work for all generators. (Specifically, if you are trying to set Xcode's GCC_VERSION, this method confuses Xcode.)
  4. For example:
  5. CC=gcc-4.2 CXX=/usr/bin/g++-4.2 cmake -G "Your Generator" path/to/your/source
  6. [edit] Method 2: use cmake -D
  7. Set the appropriate CMAKE_FOO_COMPILER variable(s) to a valid compiler name or full path on the command-line using cmake -D.
  8. For example:
  9. cmake -G "Your Generator" -D CMAKE_C_COMPILER=gcc-4.2 -D CMAKE_CXX_COMPILER=g++-4.2 path/to/your/source
  10. [edit] Method 3 (avoid): use set()
  11. Set the appropriate CMAKE_FOO_COMPILER variable(s) to a valid compiler name or full path in a list file using set(). This must be done before any language is set (ie before any project() or enable_language() command).
  12. For example:
  13. set(CMAKE_C_COMPILER "gcc-4.2")
  14. set(CMAKE_CXX_COMPILER "/usr/bin/g++-4.2")
  15. project("YourProjectName")
  16. [edit]

默認C++11是不啟用的。在src/CMakeLists.txt文件中加上這行:

  1. SET(CMAKE_CXX_FLAGS "-std=c++11") # Add c++11 functionality
然後運行

cmake ..

make VERBOSE=1

你會看到編譯的g++命令後面帶上了:

  1. /usr/bin/g++-4.7 -std=c++11

現在成功了,享受C++11吧。

更多Ubuntu相關信息見Ubuntu 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=2

Copyright © Linux教程網 All Rights Reserved