-3

I'm putting together a simple sketch to read a few sensors and have come across some odd behaviour associated with #define and #ifdef.

Here are some snippets from my code:

// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
#define GPSSYSTEM 1
#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
#endif

With this snippet the rest of the sketch compiles, but with this:

// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
//#define GPSSYSTEM 1
#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
#endif

The compile fails, claiming that the error is in some functions further down.

BTW, Mth, Day and TMZ are not used anywhere yet, not are they defined anywhere else. What is even more odd is that the error messages are announcing the erroneous line numbers to be about 12 lines removed from where they really exist in the sketch, and have no association with the declarations here. Now, this gives a clean compile:

// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
#define GPSSYSTEM 1
//#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
//#endif

as does this:

// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
//#define GPSSYSTEM 1
//#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
//#endif

I've been chasing this weirdness for a day now and am getting nowhere.

  • It's hard to pinpoint the error withouth having the actual error and code. @ARK is right, but I'm not sure if that is the error you're looking at. – Paul Apr 20 '16 at 5:41
  • Try removing all and adding one define at a time to see who the problem child is. Additionally versions 3&4 compile because you're only defining three small variables. More color on errors would've been helpful – dinotom Apr 21 '16 at 6:50
2

The #ifdef Directive you are using is one of Conditional Directive. This directive checks whether the identifier is currently defined.

In general, it has following syntax:

#ifdef identifier newline

For Arduino, you can modify your #ifdefs to following code:

#if defined(GPSSYSTEM)
    //Code here
#endif

Explaining your code snippets behaviors:

In your first code snippets, GPSSYSTEM has been defined by following line of code:

#define GPSSYSTEM 1

Now, For this code snippets, #ifdef GPSSYSTEM is true, and following variables are defined.

But, when you comment this #define GPSSYSTEM 1 line in your 2nd code snippets, GPSSYSTEM is no more defined and so #ifdef GPSSYSTEM is false, and thus following variables are not defined which result in compilation errors in your code.

Following same logic, behavior of your 3rd and 4th code snippets can be explained easily.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.