Global var in a common globals.h file and redefinition errors

Hello,
my project uses several cpp files so I put global variables in a common globals.h file.
In each cpp file I use some guard like

> #ifndef Globals_h
> #include "globals.h"
> #endif

and in globals.h file

#ifndef Globals_h
#define Globals_h

#include "BarGraphControler.h"
#include "CommunicationWithESP.h"
BarGraphControler barGraphControler;
CommunicationWithESP communicationWithESP;

#endif

Despite those guards I can't compile successfully, I get redefinition var errors like

globals.cpp:5:19: error: redefinition of 'BarGraphControler barGraphControler'

any explanation ?
Thanks
Bernard

Your guard just prevents from importing twice in the same file. but not across files, so you end up with multiple definitions

you want global variables defined (memory allocated) in a .cpp. This way you are sure it's only done once. In the .h you just declare them extern. The linker will find them where they are.

You probably do not understand the meaning of your guards. Each .cpp file is compiled separately, your construction works only inside one file.
Thus, your globals.h file will be included in the compilation as many times as you have .cpp files in your project - if there are more than one, you will get a variable redefinition error.

I misunderstood how works the #ifndef, I usually use java not cpp.

Ok so I remove the #include "globals.h" in my CommunicationWithESP.h and put

extern BarGraphControler barGraphControler;

Then I leave in globals.h

BarGraphControler barGraphControler;

And it works, thanks a lot.

The "extern" declarations should reside in the common header file. A separate .cpp file or the program main file then contains all non-extern declarations.

here is an example of organisation

globals.h

// define stuff that needs to be shared 
extern int var1;
extern long var2;
extern void func1(int);
extern void func2(long);

file1.cpp

int var1 = 22;
void func1(int x) { var1 = x;}

file2.cpp

long var2 = 33;
void func2(long x) { var2 = x;}

demo.ino

#include "globals.h"

void setup() {
  Serial.begin(115200);
  Serial.println("before");
  Serial.print("var1 = "); Serial.println(var1);
  Serial.print("var2 = "); Serial.println(var2);
  func1(100);
  func2(200);
  Serial.println("after");
  Serial.print("var1 = "); Serial.println(var1);
  Serial.print("var2 = "); Serial.println(var2);
}

void loop() {}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.