different compilation flags for C and CXX files


I’m passing warning options like this:

Yet, among my flags, I’ve got a C++ only warning (-Wold-style-cast):
set(MY_WARNING_FLAGS -Wall -Wextra -Wold-style-cast -pedantic)

When configuring and generating, everything’s fine but on building I’ve got:

[ xx%] Building C object CMakeFiles/MyProject.dir/build/CMakeFiles/3.28.3/CompilerIdC/CMakeCCompilerId.c.obj
cc1.exe: warning: command-line option '-Wold-style-cast' is valid for C++/ObjC++ but not for C

I tried:
set(MY_WARNING_FLAGS -Wall -Wextra $<$<COMPILE_LANGUAGE:CXX>:-Wold-style-cast> -pedantic)

but the generator expression is not parsed and is passed, unchanged, to the compiler command line.

This warning bothers me. How can I get rid of it?


NB Most of my projects are pure C++ but some legacy code still contain C files, yet I think that I’m giving them to a C++ frontend such as g++.

Reproducing your example:

cmake_minimum_required(VERSION 3.20 FATAL_ERROR)

project(Example LANGUAGES C CXX)

add_library(target SHARED test.c test.cpp)

set(MY_WARNING_FLAGS -Wall -Wextra $<$<COMPILE_LANGUAGE:CXX>:-Wold-style-cast> -pedantic)
target_compile_options(target PRIVATE ${MY_WARNING_FLAGS})

Has everything work as expected locally. I would first verify locally that the above example works for you.

Strange indeed.

I cleaned my cache and made a few tries and it behave as expected. Thanks to have report your test to me.

By the way. Any idea why I have CMakeCCompilerId.c being compiled with the rest of my project? I don’t see this behavior in my other project using the same framework.


Issue solved!

It was stupid: at some point in time the build directory was erroneously created under my source directory. When recursively globing in it for the list of source files (I know, it’s pure evil), I added CMakeCCompilerId.c to my list of files to compile.

Undesired directory removed and now the behavior is consistent and as expected. At least it help me see how to use generator expression to set options :grin:


1 Like