C preprocessor confusing behaviour

Viewed 61

I have shrunk my code Aplicacion.c to this minimum expression:

#if MIVAR == pirulo
#include "a_file.h"
#elif MIVAR == pepe
#include "b_file.h"
#endif

If I compile using gcc -DMIVAR=pepe Aplicacion.c, I would suppose it tries to include b_file.h, but I get the following error:

Aplicacion.c:4:10: fatal error: a_file.h: No such file or directory
#include "a_file.h"
          ^~~~~~~~~~

Even if I define inside the source:

#define MIVAR pepe

#if MIVAR == pirulo
#include "a_file.h"
#elif MIVAR == pepe
#include "b_file.h"
#endif

When I execute gcc Aplicacion.c (or gcc -E Aplicacion.c), I still get the same error.

I feel it should be obvious, but I can not find out what is happening.

Any idea?

(All of this happens in Ubuntu)

1 Answers

C preprocessor regards any undefined identifier as 0. So this one

#if MIVAR == pirulo

looks like #if 0 == 0 for the preprocessor. Even if you define it

#define MIVAR pepe

still, it tries to compare pepe with pirulo, both are undefined, so it regards them as 0.


To fix this, you can define and compare your variables to numbers.

#define pirulo 5
#define pepe 9
#define MIVAR pepe
Related