Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XCode: duplicate symbol error when using global variable

Here's my code:

A.h

class Foo
{
public:
    int bar;
};

Foo myFoo;

main.cpp

#include "A.h"
int main()
{
    myFoo.bar = 2;
    return 0;
}

Xcode gives me the error (paraphrased):

duplicate symbol _myFoo in main.o & A.o

I'd like to keep the Foo myFoo within the A.h file.

So why is XCode throwing this error and how can I rectify it?

like image 484
ryantuck Avatar asked Nov 19 '25 01:11

ryantuck


2 Answers

You define the global variable in header and it breaks the one definition rule.
Each TU where you include the header will have its own copy of the object.

You need to use extern keyword:

  1. Declare the object as extern in header.
  2. Define it one and only one source file.
  3. Include the header wherever you want to use the global variable

A.h

extern Foo myFoo;

main.cpp

#include "A.h"

Foo myFoo;

XXXX.cpp

#include "A.h"
like image 172
Alok Save Avatar answered Nov 21 '25 13:11

Alok Save


Foo myFoo; is a definition, not a declaration. Use extern Foo myFoo; for a declaration and move the definition in a single implementation file.

like image 25
Luchian Grigore Avatar answered Nov 21 '25 14:11

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!