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?
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
externkeyword:A.h
main.cpp
XXXX.cpp