Disable compiler flag for external dependencies


I am trying to compile my c++ source files with certain gcc compiler flags (namely -Wall), but not external libs. But I can’t figure out how to achieve this. I have this mock setup for my cmakelists project file:

cmake_minimum_required(VERSION 3.11)
set(CMAKE_BUILD_TYPE "Release")




add_executable(binary my_source_file1.cpp

target_compile_options(binary PRIVATE

target_link_libraries(binary efg)

However when I build the project, it also gives compiler flag warnings for the external libs I have included. How would I avoid this? I just want to get warnings for my own source files, and not any other external dependencies. I am quite novice to cmake, so not sure how to achieve this


Your CMake file looks fine, are you sure you’re getting warnings for your external sources?

You most probably get warnings for their headers when included in your source files. And that’s how a C/C++ compiler works, the settings do apply to your source with anything included.


Thanks for reply. Yeah, I am getting errors for libs added via the add_subdirectory command, as well as single header files (i.e. for both efg lib and the xyz header in the example above).
Do you happen to know any way to ‘filter’ out header/extern libs from getting warnings? I have have compiled other projects (not mine), and they seem to have filtered out any external warnings. So I assume there is some cmake functions which can tell the compiler to prevent these warnings for given libs?

There is no such kind of filter in CMake AFAIK.
If other projects are compiling fine, then it’s because they use external libraries without such problems. Or they disabled the compiler warnings (either command line or pragma).
If the authors of the external library don’t care about warnings, the code quality might be low. It’s not that difficult to get the sources clean for the default warning level and headers even for -Wall.

Hmm alright.
I have heard elsewhere that certain flags can be assigned to specific libs. E.g. if I wanted to assign -w to the efg lib (while keeping the rest of my cmake file untouched):

target_compile_options(binary PRIVATE

But when I compile, it doesn’t seem to have an effect. Is it valid to set flags per lib like that? Not sure if I am doing something wrong with my setup tbh

Yes, you’re doing that right. But this inhibits the warnings on the sources of the external library.
So for any .cpp file of your external library you should not get any warnings.

Please have a detailed look at your make output. For which source file is the compiler called and which flags were used. Those with only -w won’t emit any warnings, and those with -Wall do, even for included headers of your external library. That’s how a C/C++ compiler works.