0

main cpp file

int age;

int main(int argc, char* argv[])
{
    printf("%d", age);
    return 0;
}

testing cpp file

// global variable
int age = 20;

I have 2 cpp files (1 is main cpp file, 2nd is testing cpp file)

So I'm trying to print out a global variable (integer) from the testing cpp file in main cpp file. It's for simple linker testing. But when I do so I get an error saying there "one or more multiply defined symbols found ".

I have tried using "char" variable and that worked fine but i dont understand why "int" doesnt work

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
emir
  • 13
  • 2
  • Strong recommendation: take the [tour] that was offered when you signed up at Stackoverflow, read [ask], and read the [asking questions](https://stackoverflow.com/help/asking) section of the Help Center. – user4581301 Feb 01 '23 at 16:58
  • You'll need to use `extern`, but probably better if you solve this problem in a better way. – Chad Feb 01 '23 at 17:08

1 Answers1

1

To use a global variable like this, you'll need to prefix the declaration with extern every except where you define it.

// main.cpp
extern int age;

In some other file:

// somewhere else
extern int age;

In test.cpp (or where ever you want to define age):

// test.cpp (where you define it)
int age = 20;

Using globals like this is not something I would encourage however.

Chad
  • 18,706
  • 4
  • 46
  • 63
  • Example of how sharing globals across files can lead to big problems: [Static Initialization Order Fiasco](https://isocpp.org/wiki/faq/ctors#static-init-order). TLDR version: Initialization order in any given cpp file (more correctly a [translation unit](https://en.wikipedia.org/wiki/Translation_unit_(programming))) is fixed top to bottom, but there are no guarantees of the initialization order of the cpp files themselves. – user4581301 Feb 01 '23 at 18:11