fenix688
fenix688

Reputation: 2615

Pass CMAKE_CXX_FLAGS to target_compile_options

I'm attempting to pass all the original CMAKE_CXX_FLAGS like an argument to target_compile_options function.

CMakeLists.txt

set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -std=c++0x -Wall -pedantic -Werror -Wextra)

# I'd wish this target_compile_options
target_compile_options(my_target INTERFACE ${CMAKE_CXX_FLAGS})

This gives me an error:

g++.exe: error:  -std=c++0x -Wall -pedantic -Werror -Wextra: No such file or directory

I know a simple solution is:

target_compile_options(my_target INTERFACE -std=c++0x -Wall -pedantic -Werror -Wextra)

But I'd want to keep the original SET(CMAKE_CXX_FLAGS ...), would it be possible?

Thanks in advance!

Upvotes: 1

Views: 8353

Answers (1)

ComicSansMS
ComicSansMS

Reputation: 54589

This is probably due to the fact that CMAKE_CXX_FLAGS expects a single string (parameters are separated by spaces) while target_compile_options uses a list (parameters are separated by semicolons).

As a quick hack, you could try separating all spaces by semicolons using the string command:

 # this will probably break if you omit the "s
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x -Wall -pedantic -Werror -Wextra")

string(REPLACE " " ";" REPLACED_FLAGS ${CMAKE_CXX_FLAGS})
target_compile_options(my_target INTERFACE ${REPLACED_FLAGS})

Note that in the real world, you would never want to both set the CMAKE_CXX_FLAGS and set the target_compile_options at the same time. You should stick with one approach (in my experience target_compile_options is less likely to cause trouble in the long run) and use the correct string separators for that throughout.

Upvotes: 12

Related Questions