vitalstatistix
vitalstatistix

Reputation: 340

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:

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

*Can I assume that getting the standard number (e.g. 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.

Upvotes: 2

Views: 890

Answers (1)

David Grayson
David Grayson

Reputation: 87386

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.

Upvotes: 3

Related Questions