Skip to content

Adding compiler flags to existing CMake flags.



I have been checking out various means to add compiler options while using
the CMake build system. This was not so obvious to me when going through
all the .cmake files in my huge project. So after searching a bit the
following is the way to add custom compiler flags to cmake builds:


First define the new compiler flags
We want to add the option to optimise space/size.

set (NEW_COMPILER_OPT_FLAGS "-Os")

Then add a definition of the new flag and appen it to the existing cxx
flags.

add_definitions(${NEW_COMPILER_OPT_FLAGS})
set ( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${NEW_COMPILER_OPT_FLAGS}" )

For C based builds instead of using CMAKE_CXX_FLAGS use CMAKE_C_FLAGS.