Conditional CXX_FLAGS using cmake based on compile

2019-03-10 05:14发布

问题:

I've just started using CMake for some personal and school projects, and I've been stumped by a minor issue.

Let's say I'm trying to get a C++ program compiling under multiple compilers (g++, cl, and bcc32 in this case). I have different command line switches for each compiler, and what I was attempting to do was to basically make a gnu/ms/borland directory and create CMake stuff in there (by entering the directories and doing a cmake -DCMAKE_CXX_COMPILER=g++ .. in the gnu, directory, for instance).

In the CMakeLists.txt on the top level directory, I tried doing something along the lines of:

if(CMAKE_CXX_COMPILER STREQUAL g++)

  set(CMAKE_CXX_FLAGS "-Wextra -Wall -ansi -pedantic")

And so on with elsifs for the other compilers, but this doesn't seem to work correctly -- it drops the CXXFLAGS entirely. The line works if I make the file completely unconditional (ie, just assume g++ and use g++ flags.).

What am I doing wrong here, or is there a better way to handle this sort of a problem?

回答1:

There are a bunch of pre-defined CMake variables depending on the compiler you're using:

if (MSVC)
  set ( CMAKE_CXX_FLAGS "/GLOBAL_FLAGS_GO_HERE")
  set ( CMAKE_CXX_FLAGS_DEBUG "/DEBUG_FLAGSS_GO_HERE")
  set ( CMAKE_CXX_FLAGS_RELEASE  "/RELEASE_FLAGS_GO_HERE" )
endif ()

if (BORLAND)
  set ( CMAKE_CXX_FLAGS "/GLOBAL_FLAGS_GO_HERE")
  set ( CMAKE_CXX_FLAGS_DEBUG "/DEBUG_FLAGS_GO_HERE")
  set ( CMAKE_CXX_FLAGS_RELEASE  "/RELEASE_FLAGS_GO_HERE" )
endif ()

if (CMAKE_COMPILER_IS_GNUCXX)
  set ( CMAKE_CXX_FLAGS "/GLOBAL_FLAGS_GO_HERE")
  set ( CMAKE_CXX_FLAGS_DEBUG "/DEBUG_FLAGS_GO_HERE")
  set ( CMAKE_CXX_FLAGS_RELEASE  "/RELEASE_FLAGS_GO_HERE" )
endif ()

If you want your compiler options to override and persist in the generated CMakeCache:

if (CMAKE_COMPILER_IS_GNUCXX)

  set ( CMAKE_CXX_FLAGS "/GLOBAL_FLAGS_GO_HERE" 
        CACHE STRING "g++ Compiler Flags for All Builds" FORCE)

  set ( CMAKE_CXX_FLAGS_DEBUG "/DEBUG_FLAGS_GO_HERE"
        CACHE STRING "g++ Compiler Flags for Debug Builds" FORCE)

  set ( CMAKE_CXX_FLAGS_RELEASE  "/RELEASE_FLAGS_GO_HERE"
        CACHE STRING "g++ Compiler Flags for Release Builds" FORCE)

endif ()


标签: c++ cmake