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

浪子不回头ぞ 提交于 2019-12-24 09:27:17

问题


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:


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.



来源:https://stackoverflow.com/questions/41545768/in-cmake-how-do-i-add-to-a-compiler-flag-only-if-it-isnt-used-already

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!