I have a global that I would like to share across multiple files. Lets call it:
library.cpp:
HookContext g_context;
Then, I have two other files that I wish to access this global in:
A.cpp:
extern HookContext g_context;
B.cpp;
extern HookContext g_context;
When I link all these files together, my linker complains with the following warning:
B.obj : error LNK2005: “class HookContext g_context” (?g_context@@3VHookContext@@A) already defined in A.obj
Am I using extern incorrectly? What should I do to access the context in both A and B?
NOTE: In this case, I do not wish to use any header files to define the context.
Thanks
n.m was correct, the above code in itself is correct.
It turns out one of my lines was actually adding an extra “()” at the end of it. Like this:
extern HookContext g_context();
Which causes g_context to be initialized and instantiated in that translation unit.
When I removed the ()’s it ended up working.