For Cmake, can you modify the release/debug compiler flags with `add_compiler_flags()` command?

前端 未结 1 1742
失恋的感觉
失恋的感觉 2021-01-06 02:56

In the man page for add_compile_options() I don\'t see any mention of how to modify the Release/Debug compiler flags. Can you use add_compiler_opt

相关标签:
1条回答
  • 2021-01-06 03:19

    If you want to reuse your compiler settings through several of your projects or you need to differentiate the compiler options between C and C++, I would recommend the CMAKE_C_FLAGS/CMAKE_CXX_FLAGS variant with a toolchain file for each of your supported compilers (see e.g. here or here).

    But if you just need some additional C++ compiler options in your project, taking add_compile_options(), target_compile_options() or target_compile_features() is the way to go.

    And yes, you can differentiate between DEBUG and RELEASE there.

    Examples

    1. The add_compile_options() command does take generator expressions:

      add_compile_options("$<$<CONFIG:DEBUG>:/MDd>")
      

      or

      add_compile_options(
          "$<$<CONFIG:RELEASE>:-std=gnu99>"
          "$<$<CONFIG:DEBUG>:-std=gnu99 -g3>"
      )
      
    2. Better to check also the compiler id:

      add_compile_options("$<$<AND:$<CXX_COMPILER_ID:MSVC>,$<CONFIG:DEBUG>>:/MDd>")
      

      or

      if (MSVC)
          add_compile_options("$<$<CONFIG:DEBUG>:/MDd>")
      endif()
      
    3. Even better to let CMake decide the correct compiler options for you. So you can either set the CXX_STANDARD needed for your target:

      set_property(TARGET tgt PROPERTY CXX_STANDARD 11)
      

      or give the compiler feature your target needs with target_compile_features()

      add_library(mylib requires_constexpr.cpp)
       # cxx_constexpr is a usage-requirement
       target_compile_features(mylib PUBLIC cxx_constexpr)
      

    References

    • CMake CMAKE_CXX_FLAGS enabled optimization unexpectly
    • Change default value of CMAKE_CXX_FLAGS_DEBUG and friends in CMake
    • CMake generator expression, differentiate C / C++ code
    0 讨论(0)
提交回复
热议问题