in cmake how do I apply -std=c++11 flag for C++ code, but not for C code in the same directory

Viewed 282

In a project with a mixture of C++ and C code in one directory, I need the -std=c++11 flag to apply for the C++ code, but not the C code. (Because that causes an error on MacOS.)

Currently I do this:

add_compile_options( -std=c++11 )

However, there don't seem to be any options on the add_compile_options() function to allow me to specify that these flags should only be used for C++ files.

In autotools this would be achieved by setting CXXFLAGS for C++ and CFLAGS for C code. Is there some way to do the same in CMake?

4 Answers

Don't use add_compile_options for anything, ever! In the worst case, you can use target_compile_options, but for setting the language standard, CMake has special support that should always be preferred.

For the target you want to compile as C++11, simply write:

target_compile_features(my_target PRIVATE cxx_std_11)

You should use the target_compile_features in other answer, if not, use set_property as also presented in other answer. Still, you can pass compile_options specifically to C++ compiler with generator expression:

# prefer other answers to it
add_compile_options(
     $<$<COMPILE_LANGUAGE:CXX>:-std=c++11>
)

This can be done using

# Setting your C++ standard.
set_property(TARGET your_target PROPERTY CXX_STANDARD 11)
# Setting your C standard.
set_property(TARGET your_target PROPERTY C_STANDARD 11)

Of course the standard number has to be a supported version number:

  • For C++ this includes: 98, 11, 14, 17, 20 and 23.
  • For C this includes: 90, 99 and 11.

You do not have to use both of them. You can thus ask CMake to use C++11 while still using the default C standard.

Here is one way to do it. Note you must specify the required property. And I like to disable extensions to not rely on any compiler specific flags.

set_target_properties(myTarget
    PROPERTIES
        CXX_STANDARD 11
        CXX_STANDARD_REQUIRED YES
        CXX_EXTENSIONS NO
)
Related