7

How can I share/globalize a bool variable between A.cpp and B.cpp where neither of them does include the other ones .h file?? They have other joint header files but not each other's. Can I define the global variables inside those shared headers?

Thanks

user2517676
  • 969
  • 6
  • 15
  • 25

2 Answers2

14

Can I define the global variables inside those shared headers?

No.

In A.cpp (or) B.cpp write,

int gVariable = 10;

Remember to write the above definition in only one source file or else linker will complain of multiple symbols if you write in both the source files.

And in the common header of A.cpp, B.cpp write,

extern int gVariable;
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • +1, but although you're technically right to say "No" to "Can I define...?", I'm not sure the OP knows the difference between "define" and "declare". The answer is "Yes, you can *declare* the variable in a shared header, and *define* it in one of the source files." – RichieHindle Aug 07 '13 at 21:17
  • You are correct. I was more looking on the **define** word in the question. The `extern` in the header file is the declaration though which can be declared multiple times in various source files. – Mahesh Aug 07 '13 at 21:20
  • Thank you guys. Just a short question.... Can I put "int gVariable = 10;" inside the common header's corresponding .cpp file? – user2517676 Aug 07 '13 at 21:40
  • @user2517676 No. That would result to multiple symbols. You have to do extern declaration in a header file while the definition is given in only one source file/translation unit. – Mahesh Aug 07 '13 at 21:44
  • What I mean is declaring gVariable inside the C.h, defining it in in C.cpp while both A.cpp and B.cpp have C.h included. – user2517676 Aug 07 '13 at 21:48
1

file 1:

int x = 50;

file 2:

extern int x;
Hossein Nasr
  • 1,436
  • 2
  • 20
  • 40