I would like to add -std=c++11
to my
add_compile_options(\"-std=c++11\")
However, this also adds them to compilation of C
When you have mixed C and C++ sources, the LINKER_LANGUAGE
property might apply the wrong flags for compilation of individual sources. The solution is to use the COMPILE_LANGUAGE
generator expression (introduced with CMake 3.3). The simplest example for your original C++1x flag is:
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-std=c++11>)
When you have a string of compile options (for example, for usage with the COMPILE_FLAGS
target property), you have to split the flags
set(WARNCFLAGS "-Wall -Wextra -Wfuzzle -Wbar")
# ...
string(REPLACE " " ";" c_flags "${WARNCFLAGS}")
string(REPLACE " " ";" cxx_flags "${WARNCXXFLAGS} ${CXX1XCXXFLAGS}")
add_compile_options(
"$<$<COMPILE_LANGUAGE:C>:${c_flags}>"
"$<$<COMPILE_LANGUAGE:CXX>:${cxx_flags}>"
)
# Two alternative variants for single targets that take strings:
target_compile_options(some-target PRIVATE "${WARNCFLAGS}")
set_target_properties(some-target PROPERTIES
COMPILE_FLAGS "${WARNCFLAGS}")
Use of strings is however deprecated in favor of lists. When lists are in use, you can use:
set(c_flags -Wall -Wextra -Wfuzzle -Wbar)
# ...
add_compile_options(
"$<$<COMPILE_LANGUAGE:C>:${c_flags}>"
"$<$<COMPILE_LANGUAGE:CXX>:${cxx_flags}>"
)
# Two alternative variants for single targets given a list:
target_compile_options(some-target PRIVATE ${f_flags})
set_target_properties(some-target PROPERTIES
COMPILE_OPTIONS "${c_flags}")
Pay attention to the quoting. If a list is not quotes, it is expanded to its items (and is no longer a list). To pass a list between commands, quote it.
You can use LINKER_LANGUAGE target property to add flag only to C++ targets*:
add_compile_options(
"$<$<STREQUAL:$<TARGET_PROPERTY:LINKER_LANGUAGE>,CXX>:-std=c++11>"
)
*Note that this will not work for targets with mixed C/C++ sources
CMAKE_CXX_FLAGS should work fine too:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
Probably you need to add them to cache if it set before project
command (e.g. in toolchain):
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" CACHE STRING "" FORCE)
I'd rather do it like this:
set_source_files_properties(
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
PROPERTIES COMPILE_FLAGS "-std=c++11")
where the documentation for set_source_files_properties
is at http://www.cmake.org/cmake/help/v3.0/command/set_source_files_properties.html