Passing compiler options in CMake

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

  1. The initial content from the cached CMAKE_CXX_FLAGS variable is a combination of CMAKE_CXX_FLAGS_INIT set by CMake itself during OS/toolchain detection and whatever is set in the CXXFLAGS environment variable. So you can initially call:

     cmake -E env CXXFLAGS="-Wall" cmake ..
    
  2. Later, CMake would expect that the user modifies the CMAKE_CXX_FLAGS cached variable directly to append things, e.g., by using an editor like ccmake commit with CMake.

  3. 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).

  1. The CMAKE_EXE_LINKER_FLAGS_INIT, CMAKE_SHARED_LINKER_FLAGS_INIT or CMAKE_MODULE_LINKER_FLAGS_INIT do combine with the evironment variable LDFLAGS to CMAKE_EXE_LINKER_FLAGS, CMAKE_SHARED_LINKER_FLAGS and CMAKE_MODULE_LINKER_FLAGS.

    So you can e.g call:

     cmake -E env LDFLAGS="-rpath=/home/abcd/libs/" cmake ..
    
  2. See above.

  3. 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:

Unfortunately, there is none for the compiler’s warning level (yet)

References

Leave a Comment