Variable scope with multiple includes?

I’m attempting to port an Arduino project to use a Photon, but am having issues with variable scoping across multiple included files. I’m compiling using the Particle CLI.

In my main file, I have:

#define READY_STR "READY"
#include "comms.cpp"

In comms.cpp, I have:

void comms_ready() {
	Serial.println(READY_STR);
}

The error produced is:

comms.cpp: In function 'void comms_ready()':
comms.cpp:105:17: error: 'READY_STR' was not declared in this scope
  Serial.println(READY_STR);

I’ve tried renaming file extensions to *.cpp and/or *.ino, changing where files are included in code, where variables are defined, etc. The only fix seems to be putting the #define READY_STR at the top of the included file. I’m getting this error for all the global variables used inside of comms.cpp and other included files, so duplicating all of those global variables is less than ideal. And I definitely don’t want to merge the contents of 10+ files into one!

Any suggestions?

1 Like

@wgbartley, #defines are only local to the compile unit. The only way to avoid this is to put them in a .h include file that you include in each compile unit (.cpp file). Also, you should break comms.cpp into a comms.h (with function prototypes, etc) and a comms.cpp and include comms.h in your code. The comms.cpp will get compiled separately but get included due to the function prototypes you included in the .h and used by other .cpp files.

Thanks @peekay123! That makes much more sense now. See why I wanted you to be the owner of the RGBPongClock repo? :wink:

Did you try putting the Global defines into a generic header file (e.g. Names.h) and including that header?

That’s exactly what I just did. Now I’m getting compile failures without errors. :smile:

I’m going to try a local compile now. Might as well byte the bullet and get it set up on my dev server anyways.

1 Like