In CMake, how do I add to a compiler flag only if it isn't used already?

2.2k views Asked by At

I'm using CMake, and I want to add a compilation flag to some flags variable. For example, I want to add -DFOO to the CMAKE_CXX_FLAGS_RELEASE variable.

Right now, I use:

set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DFOO" )

... but if there already is a -DFOO flag, I get it double, which might be harmless but I'd rather avoid it. Assuming I can't control whether or not there's a -DFOO to begin with - how can I "add a flag only if it's missing" to such a flags variable?

Notes:

  • An answer regarding adding elements to a space-separated-list variable in general will suffice, I guess.
  • My CMakeLists.txt requires CMake v2.8 at the least; but if you have an answer which requires a newer version (3.x ?), that would also be relevant.
1

There are 1 answers

3
fedepad On BEST ANSWER

It seems like you could use the following syntax:

if(<variable|string> MATCHES regex)  

which according to the documentation (https://cmake.org/cmake/help/v3.0/command/if.html) evaluates to

True if the given string or variable’s value matches the given regular expression.

A minimum working example that replicates yours:

cmake_minimum_required(VERSION 2.8)

set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DFOO" )
if( CMAKE_CXX_FLAGS_RELEASE MATCHES "-DFOO")
        message("matching -DFOO")
        message("${CMAKE_CXX_FLAGS_RELEASE}")
else( CMAKE_CXX_FLAGS_RELEASE MATCHES "-DFOO")
        message("no -DFOO!!!")
        message("${CMAKE_CXX_FLAGS_RELEASE}")
endif()

will print

matching -DFOO
-O3 -DNDEBUG -DFOO

while the following

cmake_minimum_required(VERSION 2.8)

set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}" )
if( CMAKE_CXX_FLAGS_RELEASE MATCHES "-DFOO")
        message("matching -DFOO")
        message("${CMAKE_CXX_FLAGS_RELEASE}")
else( CMAKE_CXX_FLAGS_RELEASE MATCHES "-DFOO")
        message("no -DFOO!!!")
        message("${CMAKE_CXX_FLAGS_RELEASE}")
endif()

will print

no -DFOO!!!
-O3 -DNDEBUG

You could achieve similar results by using the followings:

string(REGEX MATCH <regular_expression> <output variable> <input>)  

or

string(FIND <string> <substring> <output variable>)  

the last one previously suggested by @usr1234567 in a comment.
So you could put the

set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DFOO" )  

inside the if() statement as a solution.