Search code examples
c++cmake

Different warning levels (though target_compile_options) for static library subproject in CMake


I have a CMakeLists.txt like this:

project(MyProject)
add_subdirectory(SomeLibrary)
add_executable(MyProject ${SRC_FILES})
target_compile_options(MyProject PRIVATE -Werror -Wall)
target_link_libraries(MyProject SomeLibrary)

Where SomeLibrary is a 3rd party library (linked as a git submodule) that will fail to build with -Werror -Wall

I want to build my project with -Werror -Wall, but disable -Werror for the subproject. How can I do this?

I saw a related question, but that covers the case where the flags are set directly through CMAKE_CXX_FLAGS - not target_compile_options.


Solution

  • Answering my own question (thanks to @Friedrich for pointing me in the right direction):

    Turns out target_compile_options does after all work per-target, and I had simply misread the compilation output. The errors came from a header exposed by the 3rdparty library, which was included from my own project. So the third party library builds fine, since it is built without -Werror, but my main project (which is built with _Werror) fails.

    I guess the only way to fix this is to either:

    • Fix the problematic headers yourself (and notify maintainer / make PR).
    • Use compiler-specific #pragma directives (#pragma GCC diagnostic ignored or #pragma warning on MSVC) to disable the specific warnings when including the problematic headers.