2

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)

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Does this answer your question? [How to compare strings in C conditional preprocessor-directives](https://stackoverflow.com/questions/2335888/how-to-compare-strings-in-c-conditional-preprocessor-directives) – kaylum Jul 02 '20 at 22:01
  • In short, the test expression in `#if` can only involve integers and macros that expand to integers. It can't compare strings or text. You could define `pepe` and `pirulo` to some integer values, and that would work. – Nate Eldredge Jul 02 '20 at 22:06
  • here is the relevant documentation https://en.cppreference.com/w/c/preprocessor/conditional – Tasos Papastylianou Jul 02 '20 at 22:08

1 Answers1

3

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
anatolyg
  • 26,506
  • 9
  • 60
  • 134