How to specify different compile options for C and C++?

My CMake project builds an executable consisting of C and C++ source files:


I want to specify different compile options for the .cpp and .c files. (For example, compiling the .cpp file requires the -std=c++11 flag, but gcc does not recognise that flag and so it should not be used for the .c file).

How can I achieve this?

(I am using add_compile_options() to specify the options).

You can use generator expressions to state which flags should be used by per language.

My recommendation would be to read Step 10 of the CMake tutorial:

And to manage specifically flag -std=, CMake have native support of this feature, See Compile Features.

1 Like

This is definitely the way to go. Using

target_compile_features(myAP PUBLIC cxx_std_11) will bring appropriate flags on C++ file and not on C file.

if you want to selectively set compilation options on file then you can look at:

Thanks for your answers. I am still struggling somewhat. The suggestions worked for -std=c++11, but I also want to enable ‘-pedantic’ for C++ files but not for C. I tried this:

# Enable pedantic warnings for C++ files but not C files
target_compile_options(ThebeAP PRIVATE

But it seems gcc.exe is still also using -pedantic.

Any thoughts please?

You are not using the right generator expression. $<CXX_COMPILER_ID:GNU> asks about compiler id, not the compiler used for files. So, as soon as the C++ compiler is GNU, the genex is true.

You have to define options based on compiler used for compiling files:

It is clearly explained here: $<COMPILE_LANG_AND_ID>.

Thanks. I’m afraid I have a syntax error which I can’t see how to fix from the docs:

target_compile_options(ThebeAP PRIVATE
Error evaluating generator expression:


Expression did not evaluate to a known generator expression

Maybe COMPILE_LANG_AND_ID is not available in the CMake version that you are using. It was introduced in CMake 3.15.

However, you can use a combination of regular condition and generator expression (COMPILE_LANGUAGE was introduced in CMake 3.3):

  target_compile_options(ThebeAP PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-pedantic>)

@McMartin Thank you. I upgraded to 3.16.4 and COMPILE_LANG_AND_ID then worked fine.


This is another alternative using just a combination of generator expressions:


This is also pointed out in the documentation of COMPILE_LANG_AND_ID provided by @marck.chevrier