Tag Archives: warning: extra tokens at end of #if

Gcc compiler warning solution: “extra tokens at end of ifndef directive” Tags: GCC, warning

Recently, after checking all the warnings in the project, we found an interesting warning: “extra tokens at end of ifndef directive”. Literally, “there are invalid instructions after ifndef.”. I wrote a small program verification in private, and found that there are two situations that can generate this warning.

Procedure 1:

// directive_1.c
#include <stdio.h>

#ifndef MIN
  #define MIN(x, y) ((x) > (y) ? (y) : (x)) 
#endif /**/x

int main()
{
	printf("min val = %d\n", MIN(100, -1));

	return 0;
}

The above program intentionally adds an invalid character X after “ENDIF / * * / and compiles with GCC with – wall parameter as follows:
GCC directive_ 1. C - wall - O out1
an alarm is generated immediately:

directive_1.c:5:12: warning: extra tokens at end of #endif directive [-Wendif-labels]
 #endif /**/x

I was immediately shocked. Such an obvious “error” problem was that GCC was just a warning, and generated an executable binary file to execute . / out1 . The result was normal, and the effect was as follows:

min val = -1

Procedure 2:

// directive_2.c
#include <stdio.h>

#ifndef MIN
  #define MIN(x, y) ((x) > (y) ? (y) : (x)) 
#endif

int main()
{
	printf("min val = %d\n", MIN(100, -1));

	return 0;
}

Remove the redundant “X” above, and the compilation will be completely normal. As follows:

wangkai@fiberserver:extra-tokens-at-end-of-#ifndef-directive$ gcc directive_2.c -Wall -o out1
wangkai@fiberserver:extra-tokens-at-end-of-#ifndef-directive$ 

After further divergence of the possible situation after ifndef, it is found that there is another situation that can cause this alarm.

Procedure 3:

// directive_3.c
#include <stdio.h>

#ifndef MIN(x, y)
  #define MIN(x, y) ((x) > (y) ? (y) : (x)) 
#endif

int main()
{
	printf("min val = %d\n", MIN(100, -1));

	return 0;
}

Execute the command “ GCC directive"_ 3. C - wall - O out3 , this alarm also magically appears, as follows:

wangkai@fiberserver:extra-tokens-at-end-of-#ifndef-directive$ gcc directive_3.c -Wall -o out3
directive_3.c:3:12: warning: extra tokens at end of #ifndef directive
 #ifndef MIN(x, y)
            ^

The reason is that the preprocessing of # ifndef in C language only checks the keywords, and the “(x, y)” after it is considered as redundant characters. If the brackets are removed and written as # ifndef min , there will be no alarm.