The accepted answer is still working but outdated since 2013.
This answer is based and new functions from CMake v2.8.12, v3.3 and v3.13.
Since CMake-2.8.12 (2013)
设置<条码>CMAKE_CXX_FLAGS的两个新指挥部:
最新版本的文件自cmake-2.8.12以来没有变化:
您可以使用:
target_compile_options(${TARGET} PRIVATE ${BUILD_FLAGS})
或者简单地说,如果你有一个目标:
add_compile_options(${BUILD_FLAGS})
More examples
target_compile_options(mylib PRIVATE -O2) # only internal
target_compile_options(mylib INTERFACE -gl) # only external
target_compile_options(mylib PUBLIC -g) # same as PRIVATE + INTERFACE
# multiple targets and flags
target_compile_options(mylib1 mylib2 PRIVATE -Wall -Wextra)
target_compile_options( mylib PUBLIC -DUSEXX) # Bad
target_compile_definitions(mylib PUBLIC -DUSEXX) # OK
add_compile_options(-Wall -Wextra) # for all targets in current directory
add_compile_options(-DUSEXX) # Bad
add_definitions(-DUSEXX) # OK
Deprecated COMPILE_FLAGS
cmake-3.0document signsCOMPILE_FLAGS
deprecated:
COMPILE_FLAGS
在汇编这一目标来源时,还要使用更多的旗帜。
The COMPILE_FLAGS
property sets additional compiler flags used to
build sources within the target. Use COMPILE_DEFINITIONS
to pass
additional preprocessor definitions.
This property is deprecated. Use the COMPILE_OPTIONS
property or the
target_compile_options
command instead.
如果您仍然希望使用<代码>_target_properties()。 您可使用<条码>。
set_target_properties(${TARGET} PROPERTIES COMPILE_OPTIONS ${BUILD_FLAGS})
Since CMake-3.3 (2015)
rel=“noreferer”>>,如在上所示。
CMake generator expression 适用于${BUILD_FLAGS}/code>:
- C++ language using
$<COMPILE_LANGUAGE:CXX>
(can also be C
, CUDA
...)
- Clang compiler using
$<CXX_COMPILER_ID:Clang>
(can also be GNU
for gcc
, or MSVC
for Visual C++... see full list)
(use $<C_COMPILER_ID:Clang>
instead if language is C)
- and more as supported C++ feature or compiler version... (see documentation)
您可以使用:
target_compile_options(${TARGET} PRIVATE
$<$<COMPILE_LANGUAGE:CXX>:${BUILD_FLAGS_FOR_CXX}>
$<$<COMPILE_LANGUAGE:C>:${BUILD_FLAGS_FOR_C}>)
或大约汇编者:
target_compile_options(${TARGET} PRIVATE
$<$<CXX_COMPILER_ID:Clang>:${BUILD_FLAGS_FOR_CLANG}>
$<$<CXX_COMPILER_ID:GNU>:${BUILD_FLAGS_FOR_GCC}>
$<$<CXX_COMPILER_ID:MSVC>:${BUILD_FLAGS_FOR_VISUAL}>)
Since CMake-3.13 (2018)
新的职能target_link_options (
如
Different options for C and C++ files
最好的办法是利用两个不同的目标来区分C文档和C++文档。