Yes, you can append compiler and linker options. But there are two things you have to differentiate in CMake: the first call to generate the build environment and all consecutive calls for regenerating that build environment after changes to your CMakeLists.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_FLAGSvariable is a combination ofCMAKE_CXX_FLAGS_INITset by CMake itself during OS/toolchain detection and whatever is set in theCXXFLAGSenvironment variable. So you can initially call:cmake -E env CXXFLAGS="-Wall" cmake .. -
Later, CMake would expect that the user modifies the
CMAKE_CXX_FLAGScached variable directly to append things, e.g., by using an editor likeccmakecommit 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_INITorCMAKE_MODULE_LINKER_FLAGS_INITdo combine with the evironment variableLDFLAGStoCMAKE_EXE_LINKER_FLAGS,CMAKE_SHARED_LINKER_FLAGSandCMAKE_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 a 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_STANDARDCMAKE_POSITION_INDEPENDENT_CODECMAKE_BUILD_RPATHCMAKE_INSTALL_RPATH_USE_LINK_PATH
Unfortunately, there is none for the compiler’s warning level (yet)
References
- Change default value of CMAKE_CXX_FLAGS_DEBUG and friends in CMake
- How to set warning level in CMake?