c++cmakecompiler-errors

How can I set different compiler options for a single header file?


I have a CMAKE file with the following compilation flags

 set (CMAKE_CXX_FLAGS_DEBUG  "${CMAKE_CXX_FLAGS_DEBUG} \
    -fPIC -Wall -pedantic -Wextra -Werror \
    -Wno-missing-braces -Wno-unused-variable \
    -Wno-ignored-qualifiers  -fdiagnostics-color")

I want to omit the -Wextra option for a single header file; /externals/include/foo.hpp (this is a third-party header-only library and gives error: [-Werror=unused-parameter] when compiled).

I have tried set_source_files_properties like this

set_source_files_properties(${EXTERNALS_SOURCE_DIR}/foo.hpp PROPERTIES COMPILE_FLAGS  "${CMAKE_CXX_FLAGS_DEBUG} -Wno-extra")

but couldn't get rid of the compilation error.

Is there a way to do that either in CMAKE or using #pragmas in the header file itself?

Thanks.

SOLUTION Here is how I got rid of the error:

` // In file foo_wrapper.hpp:

   _Pragma("GCC diagnostic push")

   _Pragma("GCC diagnostic ignored \"-Wunused-parameter\"")

   #include "foo.hpp"

   _Pragma("GCC diagnostic pop")

`


Solution

  • On current compilers, it is not possible to do this through build options.

    This is because of how the build model works: The compiler will get invoked once for every source file and all the header files included by that source file will invariably use the same build options as the source file itself. So CMake will not be able to help you here.

    Some compilers allow switching off certain warnings through #pragmas. For example, MSVC or gcc. Check your compiler's manual for what they offer in this regard. Unfortunately, this will always be non-portable, so if you have a code base supporting lots of compilers, the #pragmas can get lengthy. I would recommend writing a wrapper header that only includes the third party header giving you trouble and takes care of all the warning disabling. In your project you then always include the wrapper instead of the original third party header.