Fwd: [CMake] Globally add compiler options for gcc

James Bigler bigler at cs.utah.edu
Fri Jan 4 12:47:40 EST 2008


> 2008/1/4, Stephen Collyer <scollyer at netspinner.co.uk>:
>> This is almost certainly a FAQ but I can't find
>> an answer anywhere: I'm building using gcc under
>> Linux and VS2005 under Win32. I want to add, say,
>> -Wall globally to everything compiled under Linux
>> but leave the compile options for Win32 untouched.
> 
> You may put in your main CMakeLists.txt
> 
> IF(UNIX)
>     IF(CMAKE_COMPILER_IS_GNUCC)
>          ADD_DEFINITION(-Wall)
>     ENDIF(CMAKE_COMPILER_IS_GNUCC)
> ENDIF(UNIX)
> 
> This example checks for being under UNIX and GCC is the compiler.
> If you want to restrict to Linux you should add a test
> for CMAKE_SYSTEM_NAME value to match "Linux".
> 
> In this particular case and if you only compile C code
> you may replace ADD_DEFINITIONS with:
> 
> SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall")

Doing it this way will most certainly give you grief, unless you add bit 
more infrastructure.  First off, every time you run cmake, it will add 
another -Wall to your CMAKE_C_FLAGS.  Also, I'm a little unsure of this, 
but it may not even set the flags properly without a FORCE in the 
command.  Also, you will find it hard for a user to turn it off if they 
don't wish to see it for some reason.

You have a couple of ways to help you out.  If you wish to force this 
flag on all the time use the following macro:

http://www.cmake.org/Wiki/CMakeMacroForceAddFlags

It will force the addition of a flag and make sure there is only one 
copy of the flag.

If you wish to provide a reasonable default and allow the user to change 
it afterwards, the task gets much more hairy as you must detect when the 
first time you have run CMake and only modify the flags then.

I haven't verified this (as I discovered this much later after 
implementing the second option above for a project), but these variables 
may be of interest:

  CMAKE_C_FLAGS_INIT
  CMAKE_CXX_FLAGS_INIT

I don't know if modifying these flags would allow you to create new 
"defaults".

James


More information about the CMake mailing list