Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler flags for C++11

Tags:

c++11

cmake

I'm trying to write a CMakeFiles.txt (never done it before) and I'm not sure what compiler flag to use for C++11. I use GCC 4.8.2 and the flag is std=c++0x but I'm not sure what to do about other compilers. I don't suppose they all use that flag, I believe MinGW-TDM uses std=c++11, what would the correct way to ensure the compiler uses c++11 be?

like image 608
Mike Avatar asked Oct 03 '22 08:10

Mike


2 Answers

In my project I just try to add -std=c++11 and if that does not work I try -std=c++0x. When both fail, I just leave it alone. For me that works great but I have never tried a Windows compiler. Here an example code:

# test for C++11 flags
include(TestCXXAcceptsFlag)

if(NOT DISABLE_GXX0XCHECK)
  # try to use compiler flag -std=c++11
  check_cxx_accepts_flag("-std=c++11" CXX_FLAG_CXX11)
endif(NOT DISABLE_GXX0XCHECK)

if(CXX_FLAG_CXX11)
  [add flag -std=c++11 where needed]
else()
  if(NOT DISABLE_GXX0XCHECK)
    # try to use compiler flag -std=c++0x for older compilers
    check_cxx_accepts_flag("-std=c++0x" CXX_FLAG_CXX0X)
  endif(NOT DISABLE_GXX0XCHECK)
  if(CXX_FLAG_CXX0X)
    [add flag -std=c++11 where needed]
...

Mabye stackoverflow.com/q/10984442 does help you, too. Erik Sjölund suggest to have a look at CMake nightly build's FindCXXFeatures.cmake.

Edit: I tried this with Microsoft's Visual C++ and my solution has a flaw: The compiler emits a warning about the unrecognized flag. This means CMake detects the flag as correct and adds it. Thus one gets this warning for every executable. Adding -Werror, or whatever the flag for Visual C++ is, should help.

like image 68
usr1234567 Avatar answered Nov 14 '22 19:11

usr1234567


You need to set your flags manually for each compiler you're targeting:

IF (CMAKE_COMPILER_IS_GNUCXX)
  SET (CMAKE_CXX_FLAGS "-std=gnu++11")
ELSEIF (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
  SET (CMAKE_CXX_FLAGS "-std=c++11")
ELSEIF (MSVC)
  # On by default
ENDIF ()

As a for instance.

like image 37
OmnipotentEntity Avatar answered Nov 14 '22 19:11

OmnipotentEntity