简体   繁体   中英

CMAKE - How to set different compiler options for a single 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:

  • Create a file foo_wrapper.hpp.
  • Add _pragma to ignore the trouble maker compilation flag
  • Use the wrapper header everywhere in the project instead of the actual header.

` // In file foo_wrapper.hpp:

   _Pragma("GCC diagnostic push")

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

   #include "foo.hpp"

   _Pragma("GCC diagnostic pop")

`

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 #pragma s. 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 #pragma s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM