At the beginning of my CMake project, I'm setting general compilation flags in the variable CMAKE_CXX_FLAGS, like
set(CMAKE_CXX_FLAGS "-W -Wall ${CMAKE_CXX_FLAGS}")
Later on, I need to append additional configuration-specific compilation flags (stored in BUILD_FLAGS). Can I use the following command for this:
set_target_properties(${TARGET} PROPERTIES COMPILE_FLAGS ${BUILD_FLAGS})
or do I have to add the CMAKE_CXX_FLAGS manually:
set_target_properties(${TARGET} PROPERTIES COMPILE_FLAGS "${CMAKE_CXX_FLAGS} ${BUILD_FLAGS}")
to prevent CMAKE_CXX_FLAGS being overriden by BUILD_FLAGS?
Use the first one:
The flags stored in BUILD_FLAGS are appended after CMAKE_CXX_FLAGS when compiling the sources of TARGET. The documentation hints at this, but I've just tried it to make sure.
The full command line will be the equivalent of:
And as Ramon said, you can always check with
make VERBOSE=1
.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)
Two new commands to set
CMAKE_CXX_FLAGS
:target_compile_options()
(for one single target)add_compile_options()
(for all targets)The documentation of last version has not changed a lot since cmake-2.8.12:
target_compile_options()
add_compile_options()
In you case you can use:
Or simply if you have a single target:
More examples
Deprecated
COMPILE_FLAGS
cmake-3.0 documentation flags
COMPILE_FLAGS
as deprecated:If you still want to use
set_target_properties()
you may useCOMPILE_OPTIONS
instead ofCOMPILE_FLAGS
:Since CMake-3.3 (2015)
Anton Petrov suggests to use generator expressions as presented in an answer of ar31.
The CMake generator expressions applies your
${BUILD_FLAGS}
to:$<COMPILE_LANGUAGE:CXX>
(can also beC
,CUDA
...)$<CXX_COMPILER_ID:Clang>
(can also be
GNU
forgcc
, orMSVC
for Visual C++... see full list)(use
$<C_COMPILER_ID:Clang>
instead if language is C)In you case you can use:
or about compilers:
Since CMake-3.13 (2018)
A new function
target_link_options()
allow to pass options to the linker, as mentioned by Craig Scott.Different options for C and C++ files
The best way is to distinguish C files and C++ files using two different targets.