I want to pass the -Werror
argument to gcc during compilation. The issue is that the code I am compiling has pragma statements such as:
#pragma GCC warning "Custom warning message"
I should be able to add an argument like -Wno-error=pragmas
to the command line to enable retaining these lines as warnings. However, when I grepped the output of gcc --help=warnings
for pragma
, user
, and explicit
, I can't find the name of the warning switch I need to use. Does anyone know how to exclude explicit #pragma
warnings from being errors when -Werror
is enabled?
I've also tried to modify the #pragma
to the following, which the GCC documentation seems to indicate should also accomplish this:
#pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wall"
#pragma GCC warning "Custom warning message"
#pragma GCC diagnostic pop
My GCC version is 11.4.0.
Reasons can be adduced from the GCC documentation why the things you have attempted do not work but I take it you don't need further convincing and just want a solution.
Replace:
#pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wall"
#pragma GCC warning "Custom warning message"
#pragma GCC diagnostic pop
with:
#pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wcpp"
#warning "Custom warning message"
#pragma GCC diagnostic pop
as in e.g.:
$ cat main.c
#pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wcpp"
#warning "Custom warning message"
#pragma GCC diagnostic pop
int main(void)
{
int x; // unused
return 0;
}
-Wcpp
is enabled by default and in man gcc
is documented only negatively:
-Wno-cpp
(C, Objective-C, C++, Objective-C++ and Fortran only)
Suppress warning messages emitted by "#warning" directives
Compile like:
$ gcc -c -Wunused -Werror main.c
main.c:3:2: warning: #warning "Custom warning message" [-Wcpp]
3 | #warning "Custom warning message"
| ^~~~~~~
main.c: In function ‘main’:
main.c:8:13: error: unused variable ‘x’ [-Werror=unused-variable]
8 | int x; // unused
| ^
cc1: all warnings being treated as errors
You custom warning remains a warning in the presence of -Werror
. That is because
such custom warnings are enabled by -Wcpp
; they are promoted to errors by -Werror
, but can be demoted to warnings again,
for the duration, by:
#pragma GCC diagnostic warning "-Wcpp"
The error: unused variable ‘x’
shows that -Werror
comes back into effect after:
#pragma GCC diagnostic pop
promoting the -Wunused
warning to an error.