Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any C compilers that'll warn about using undeclared defines

Tags:

c

I came across the situation recently where the following construct

#if BYTE_ORDER == LITTLE_ENDIAN
   do_something();
#endif

results in 'do_something()' being compiled if neither BYTE_ORDER nor LITTLE_ENDIAN are defined. Whilst this isn't unreasonable behaviour, I can't find any option on gcc to give me a warning in this situation.

Without a warning you can get into the rather worrying situation where someone can remove an apparently unused header and it will completely change the result of the compilation, because it caused to be included a header that defined those two macros (and defined them differently).

like image 481
Tom Tanner Avatar asked May 29 '15 09:05

Tom Tanner


1 Answers

From man gcc:

-Wundef
    Warn if an undefined identifier is evaluated in an #if directive.

Thus:

echo -e '#if BYTE_ORDER == LITTLE_ENDIAN\n#endif'|gcc -E - -Wundef

Prints:

# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "<stdin>"
<stdin>:1:5: warning: "BYTE_ORDER" is not defined [-Wundef]
<stdin>:1:19: warning: "LITTLE_ENDIAN" is not defined [-Wundef]

And it gets even better with -Werror=undef. 😉

like image 60
Biffen Avatar answered Sep 28 '22 00:09

Biffen