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

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

add_executable(myAP
    main.cpp
    DpdkSock.c
    <snip>
)

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 https://cmake.org/cmake/help/v3.16/command/target_compile_features.html.

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:
https://cmake.org/cmake/help/v3.16/command/set_source_files_properties.html

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
     $<$<CXX_COMPILER_ID:GNU>:
          -pedantic>)

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:
$<$<COMPILE_LANG_AND_ID:CXX,GNU>:-pedantic>.

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
                       $<$<COMPILE_LANG_AND_ID:CXX,GNU>:
                           -pedantic>)
Error evaluating generator expression:

$<COMPILE_LANG_AND_ID:CXX,GNU>

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):

if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
  target_compile_options(ThebeAP PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-pedantic>)
endif()

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

2 Likes

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

$<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CXX_COMPILER_ID:GNU>>:-pedantic>

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