Question

I have found a problem that just works fine in C but causing problems for Arduino (on Windows)

#define NO_PROBLEM
#ifdef NO_PROBLEM
  char charBuf[16];
  unsigned int numBuf;
#endif

void setup() {
}
void loop() {
}

This code just works fine. But if I change

#define NO_PROBLEM

to

//#define NO_PROBLEM

the compiler will return with the following error:

core.a(main.cpp.o): In function main: C:\Users\user\arduino-1.0.4-windows\arduino-1.0.4\hardware\arduino\cores\arduino/main.cpp:5: undefined reference to setup C:\Users\user\arduino-1.0.4-windows\arduino-1.0.4\hardware\arduino\cores\arduino/main.cpp:15: undefined reference to loop

This is part of some debugging macros and I want some variables to be there only in DEBUG mode, so actually NO_PROBLEM is DEBUG in my code.

Was it helpful?

Solution

This is a bug in the IDE that happens in connection with the prototype generation. Change the IDE settings to verbose compiler output. If you look into the build directory and search for the generated .cpp file you will see the following:

//#define NO_PROBLEM
#ifdef NO_PROBLEM
  #include "Arduino.h"
void setup();
void loop();
char charBuf[16];
  unsigned int numBuf;
#endif

void setup() {
}
void loop() {
}

vs.

#define NO_PROBLEM
#ifdef NO_PROBLEM
  #include "Arduino.h"
void setup();
void loop();
char charBuf[16];
  unsigned int numBuf;
#endif

void setup() {
}
void loop() {
}

This explains why the compiler will not compile with the comment.

A workaround is to ensure that there is something that the IDE can pick up before the macro definition which will be optimized away by the compiler. For example

namespace trick17 {};
//#define NO_PROBLEM
#ifdef NO_PROBLEM
  char charBuf[16];
  unsigned int numBuf;
#endif

void setup() {
}
void loop() {
}

Now the generated .cpp file becomes

#include "Arduino.h"
void setup();
void loop();
namespace trick17 {};
//#define NO_PROBLEM
#ifdef NO_PROBLEM
  char charBuf[16];
  unsigned int numBuf;
#endif

void setup() {
}
void loop() {
}

And this compiles OK.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top