1

How do we make a variable global across over all .cpp files/modules of a (will-be) single binary, which is to be compiled and linked by g++ in a line?

even if it's been defined in main and has extern in var. to be included in every .cpp

extern int a_sample_var;

tried it for more a week only to fail,

.....: undefined reference to a_sample_var .....

Any generous guru helping me out?

  • Global is a bad idea. Though you can introduce it to a namespace you use still not nice – Oblivion Oct 15 '19 at 06:32
  • 3
    Add it to a header and include it in all source files. – Thomas Sablik Oct 15 '19 at 06:32
  • 2
    Possible duplicate of [How do I use extern to share variables between source files?](https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files) – 273K Oct 15 '19 at 06:38

1 Answers1

1
extern int a_sample_var;

Tells the compiler: there is a int named a_simple_var defined somewhere else (think about the keyword extern: it's abbreviation for external, meaning "somewhere else"). Just leave a placeholder there and wait for the linker to find it!

Well if you do this in every cpp file (by including a header), then everyone is crying for the definition (by providing a declaration), but with no one to provide the definition. Be aware of the wording here, definition and declaration are different stuff.

In exactly one cpp file, you shall provide a definition of a_simple_var. Just simply remove the extern:

int a_sample_var;          // Initialize with 0

or

int a_sample_var = 1;      // Initialize with 1.

Those two are proper definitions.

ph3rin
  • 4,426
  • 1
  • 18
  • 42
  • In my experience people complain about not explicitly writing `... = 0`, which is why I'd suggest `int a_sample_var = 0;` instead. But in a more open minded environment both might be ok. – nada Oct 15 '19 at 06:57