Get the full C ++ compiler command line

In CMake, flags for the C ++ compiler can undergo various influences: setting CMAKE_CXX_FLAGS manually, using add_definitions() , forcing a specific C ++ standard, etc.

To compile the target in the same project with different rules (a precompiled header, in my case), I need to play the exact command that is used to compile the files added by the add_executable() command in this directory.

Reading CMAKE_CXX_FLAGS returns only the value set explicitly in it, CMAKE_CXX_FLAGS_DEBUG , and siblings list only the default Debug / Release parameters. There are special functions for extracting flags from add_definitions() and add_compiler_options() , but no one seems to be able to return the final command line.

How can I get all the flags passed to the compiler in a CMake variable?

+6
source share
2 answers

To answer my own question: it seems the only way to get all the compiler flags is to restore them from different sources. The code I'm working with is the following (for GCC):

 macro (GET_COMPILER_FLAGS TARGET VAR) if (CMAKE_COMPILER_IS_GNUCXX) set(COMPILER_FLAGS "") # Get flags form add_definitions, re-escape quotes get_target_property(TARGET_DEFS ${TARGET} COMPILE_DEFINITIONS) get_directory_property(DIRECTORY_DEFS COMPILE_DEFINITIONS) foreach (DEF ${TARGET_DEFS} ${DIRECTORY_DEFS}) if (DEF) string(REPLACE "\"" "\\\"" DEF "${DEF}") list(APPEND COMPILER_FLAGS "-D${DEF}") endif () endforeach () # Get flags form include_directories() get_target_property(TARGET_INCLUDEDIRS ${TARGET} INCLUDE_DIRECTORIES) foreach (DIR ${TARGET_INCLUDEDIRS}) if (DIR) list(APPEND COMPILER_FLAGS "-I${DIR}") endif () endforeach () # Get build-type specific flags string(TOUPPER ${CMAKE_BUILD_TYPE} BUILD_TYPE_SUFFIX) separate_arguments(GLOBAL_FLAGS UNIX_COMMAND "${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_${BUILD_TYPE_SUFFIX}}") list(APPEND COMPILER_FLAGS ${GLOBAL_FLAGS}) # Add -std= flag if appropriate get_target_property(STANDARD ${TARGET} CXX_STANDARD) if ((NOT "${STANDARD}" STREQUAL NOTFOUND) AND (NOT "${STANDARD}" STREQUAL "")) list(APPEND COMPILER_FLAGS "-std=gnu++${STANDARD}") endif () endif () set(${VAR} "${COMPILER_FLAGS}") endmacro () 

This can be extended to also include options called by add_compiler_options() and more.

+3
source

The easiest way is to use make VERBOSE=1 when compiling.

 cd my-build-dir cmake path-to-my-sources make VERBOSE=1 

This will do a single-threaded build, and make will print every shell command it runs before running it. So you will see the output, for example:

 [ 0%] Building CXX object Whatever.cpp.o <huge scary build command it used to build Whatever.cpp> 
+2
source

All Articles