获取完整的C ++编译器命令行 [英] Get full C++ compiler command line
问题描述
在CMake中,可以通过多种方式影响C ++编译器的标志:使用 add_definitions()$ c手动设置
CMAKE_CXX_FLAGS
$ c>,强制采用某种C ++标准,依此类推。
In CMake, the flags for the C++ compiler can be influenced in various ways: setting CMAKE_CXX_FLAGS
manually, using add_definitions()
, forcing a certain C++ standard, and so forth.
为了在同一项目中使用不同的规则编译目标(在我的情况下为预编译头) ),我需要重现用于编译由该目录中的 add_executable()
之类的命令添加的文件的确切命令。
In order to compile a target in the same project with different rules (a precompiled header, in my case), I need to reproduce the exact command that is used to compile files added by a command like add_executable()
in this directory.
读取 CMAKE_CXX_FLAGS
仅返回显式设置的值, CMAKE_CXX_FLAGS_DEBUG
和同级仅列出默认的Debug /释放选项。有一个特殊的功能可以从 add_definitions()
和 add_compiler_options()
中检索标志,但是似乎无法返回最后的命令行。
Reading CMAKE_CXX_FLAGS
only returns the value set to it explicitly, CMAKE_CXX_FLAGS_DEBUG
and siblings only list default Debug/Release options. There is a special functions to retrieve the flags from add_definitions()
and add_compiler_options()
, but none seem to be able to return the final command line.
如何将所有传递给编译器的标志放入CMake变量中?
How can I get all flags passed to the compiler into a CMake variable?
推荐答案
要回答我自己的问题:似乎获取所有编译器标志的唯一方法是从各种来源重构它们。我现在使用的代码如下(对于GCC):
To answer my own question: It seems like the only way of getting all compiler flags is to reconstruct them from the various sources. The code I'm working with now 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 ()
这可以扩展为还包括由 add_compiler_options()
等引发的选项。
This could be extended to also include options induced by add_compiler_options()
and more.
这篇关于获取完整的C ++编译器命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!