简体   繁体   中英

How do I get the C++ standard flag as a string in CMake?

I need to get the compiler flags that will be used to compile a target programmatically in CMake. I need these flags as a string because I need to pass them to an executable in a custom command that needs to know how the parent target was compiled because it propagates those flags. I know enabling compile commands generates a JSON that shows the compile command but I need that output in CMake itself.

project(foo LANGUAGES CXX)
cmake_minimum_required(VERSION 3.22)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_executable(bar bar.cpp)

# define COMPILE_FLAGS somehow such that it equals -std=c++17    

add_custom_target(external
    COMMAND external_exe --flags ${COMPILE_FLAGS}
)

I've looked at these previous questions:

  • Using something like this or this does print compile flags like "-Werror" but the standard flag is not printed
  • Setting the standard with set_property and then getting it returns "17". Similarly, I can get the CMAKE_CXX_STANDARD to also return "17"*
  • This is the exact problem I have but the answer doesn't help in CMake
  • These questions are also related but unhelpful: one , two , and three

Am I missing something or is there no way to get this information?

*Can I assume that getting the standard number (eg 17) and appending that to "-std=c++" will be portably valid? It works with g++ at least but I'm not sure about other compilers/platforms.

If you just need the compiler flag for choosing the C++ standard, try this:

set(COMPILE_FLAG ${CMAKE_CXX${CMAKE_CXX_STANDARD}_STANDARD_COMPILE_OPTION})

Alternatively, replace "STANDARD" in the code above with "EXTENSION" if you want to allow compiler-specific extensions.

I grepped through the CMake source code, and I found that variables like CMAKE_CXX17_STANDARD_COMPILE_OPTION are defined in files that tell CMake how to use different compilers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM