Yes, you can append compiler and linker options. But there are two things you have to differentiate in CMake: first call to generate the build environment and all consecutive calls for re-generating that build environment after changes to your CMakeList.txt
files or dependencies.
Here are some of the possibilities (excluding the more complex toolchain variants):
Append Compiler Flags
-
The initial content from the cached
CMAKE_CXX_FLAGS
variable is a combination ofCMAKE_CXX_FLAGS_INIT
set by CMake itself during OS/toolchain detection and whatever is set in theCXXFLAGS
environment variable. So you can initially call:cmake -E env CXXFLAGS="-Wall" cmake ..
-
Later CMake would expect that the user modifies the
CMAKE_CXX_FLAGS
cached variable directly to append things e.g. by using an editor likeccmake
commit with CMake. -
You can easily introduce your own build type like
ALL_WARNINGS
. The build type specific parts are appended:cmake -DCMAKE_CXX_FLAGS_ALL_WARNINGS:STRING="-Wall" -DCMAKE_BUILD_TYPE=ALL_WARNINGS ..
Append Linker Flags
The linker options are more or less equivalent to the compiler options. Just that CMake’s variable names depend on the target type (EXE
, SHARED
or MODULE
).
-
The
CMAKE_EXE_LINKER_FLAGS_INIT
,CMAKE_SHARED_LINKER_FLAGS_INIT
orCMAKE_MODULE_LINKER_FLAGS_INIT
do combine with the evironment variableLDFLAGS
toCMAKE_EXE_LINKER_FLAGS
,CMAKE_SHARED_LINKER_FLAGS
andCMAKE_MODULE_LINKER_FLAGS
.So you can e.g call:
cmake -E env LDFLAGS="-rpath=/home/abcd/libs/" cmake ..
-
See above.
-
Build type specific parts are appended:
cmake -DCMAKE_SHARED_LINKER_FLAGS_MY_RPATH:STRING="-rpath=/home/abcd/libs/" -DCMAKE_BUILD_TYPE=MY_RPATH ..
Alternatives
Just be aware that CMake does provide special variable to set complier/linker flags in a platform independent way. So you don’t need to know the specific compiler/linker option.
Here are some examples:
CMAKE_CXX_STANDARD
CMAKE_POSITION_INDEPENDENT_CODE
CMAKE_BUILD_RPATH
CMAKE_INSTALL_RPATH_USE_LINK_PATH
Unfortunately there is none for the compiler’s warning level (yet)