Change default value of CMAKE_CXX_FLAGS_DEBUG and friends in CMake

前端 未结 1 1518
[愿得一人]
[愿得一人] 2020-11-27 20:25

I would like to change the default values for CMAKE_CXX_FLAGS_RELEASE or CMAKE_CXX_FLAGS_DEBUG in CMake. Basically, I have some project defaults th

相关标签:
1条回答
  • 2020-11-27 21:11

    I just wanted to add the four possibilities I see:

    1. Having your own toolchain files containing the presets for each compiler you support like:

      GNUToolchain.cmake

      set(CMAKE_CXX_FLAGS_DEBUG "-ggdb3 -O0" CACHE STRING "")
      

      And then use it with

      cmake -DCMAKE_TOOLCHAIN_FILE:string=GNUToolchain.cmake ...
      
    2. You can try to determine the compiler by checking CMAKE_GENERATOR (which is valid before the project() command):

      CMakeLists.txt

      if("${CMAKE_GENERATOR}" MATCHES "Makefiles" OR 
         ("${CMAKE_GENERATOR}" MATCHES "Ninja" AND NOT WIN32))
          set(CMAKE_CXX_FLAGS_DEBUG "-ggdb3 -O0" CACHE STRING "")
      endif()
      
      project(your_project C CXX)
      
    3. You can use CMAKE_USER_MAKE_RULES_OVERRIDE to give a script with your own ..._INIT values:

      It is loaded after CMake’s builtin compiler and platform information modules have been loaded but before the information is used. The file may set platform information variables to override CMake’s defaults.

      MyInitFlags.cmake

      # Overwrite the init values choosen by CMake
      if (CMAKE_COMPILER_IS_GNUCXX)
          set(CMAKE_CXX_FLAGS_DEBUG_INIT "-ggdb3 -O0")
      endif()
      

      CMakeLists.txt

      set(CMAKE_USER_MAKE_RULES_OVERRIDE "MyInitFlags.cmake")
      
      project(your_project C CXX)
      
    4. You can simplify your solution from March 1st by checking against the ..._INIT variants of the compiler flag variables:

      CMakeLists.txt

      project(your_project C CXX)
      
      if (DEFINED CMAKE_CXX_FLAGS_DEBUG_INIT AND  
          "${CMAKE_CXX_FLAGS_DEBUG_INIT}" STREQUAL "${CMAKE_CXX_FLAGS_DEBUG}")
          # Overwrite the init values choosen by CMake
          if (CMAKE_COMPILER_IS_GNUCXX)
              set(CMAKE_CXX_FLAGS_DEBUG "-ggdb3 -O0" CACHE STRING "" FORCE)
          endif()
      endif()
      

    Comments:

    I prefer and use the toolchain variant. But I admit it has the disadvantage of having to give the toolchain file manually (if you are not calling cmake via a script/batch file).

    References:

    • CMake: In which Order are Files parsed (Cache, Toolchain, …)?
    • cmake - Global linker flag setting (for all targets in directory)
    • Switching between GCC and Clang/LLVM using CMake
    0 讨论(0)
提交回复
热议问题