Why do #ifdef macro's stop the sketch from compiling



Occasionally  people encounter a situation where certain scenarios of preprocessing code cause a sketch to suddenly stop compiling. This is nothing to do with C++, or weather Arduino supports the feature, but a result of how the IDE modifies your code. For a detailed explanation, see the FAQ entry 'What does the IDE change in my sketch'.

 Below is a small example sketch that demonstrates the failure to include Arduino.h properly. The compiler will report that setup() and loop() are undefined. 

#ifdef NOT_DEFINED
  bool SomeBool = true;
#endif

void setup(){
}

void loop(){
}

 The next snippet is the code after the IDE has modified in its preperation for compiling.

#line 1 "sketch_dec26a.ino"

#ifdef NOT_DEFINED
  #include "Arduino.h"
void setup();
void loop();
#line 3
bool SomeBool = true;
#endif

void setup(){
}

void loop(){
}

In the above example you can see how the IDE has added the line #include "Arduino.h" into the #ifdef block. Unfortunatly as NOT_DEFINED is, well... not defined, the include is never seen by the compiler.

The reason the IDE fails in this situation is due to how it decides where to add the include. The sketch is scanned from the top and when it hits what it considers the first line of code, it will add the include and generated prototypes above it. The IDE ignores #define and #ifdef statements and as a result, the first line is taken as bool Somebool = true;.

During scanning, even though most preprocessors are ignored, the IDE will stop on includes, so the snippet below will work having an include above the #ifdef.

#include <SPI.h>

#ifdef NOT_DEFINED
  bool SomeBool = true;
#endif

void setup(){
}

void loop(){
}

If you do not have any additional includes to add, you can simply include Arduino.h yourself. Alternatively a variable at the top of your sketch will have the same effect.

char dummy;
 
#ifdef NOT_DEFINED
  bool SomeBool = true;
#endif
 
void setup(){
}
 
void loop(){
}

Hopefully this clears up some doubt, I have run into this situation before and fully understand the frustration some of you may be going through.

Tags: error, ifdef, undefined
Last update:
2014-02-28 15:03
Author:
Christopher Andrews
Revision:
1.1
Average rating: 5 (2 Votes)

You can comment this FAQ

Chuck Norris has counted to infinity. Twice.

Comment of Dirk:
this is very interesting, thanks for sharing it. Is this behaviour still this way in the actual IDE ... show more1.6.6
Added at: 2015-11-19 16:07