1

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

JoshG
  • 775
  • 1
  • 7
  • 19
  • No, A and B are completely different files defining behavior of completely different classes. – JoshG Feb 06 '12 at 05:23
  • Answered brilliantly over [here](http://stackoverflow.com/questions/1433204/what-are-extern-variables-in-c) – bluefalcon Feb 06 '12 at 05:24
  • AFAIK you need to use headers to do it correctly – fileoffset Feb 06 '12 at 05:36
  • Since A and B use exactly the same code... isn't this essentially the same as using #include anyway (aside from maintainability issues)? – JoshG Feb 06 '12 at 05:38
  • Ravi - I'm currently reading through that large post.. I haven't spotted anything I'm doing wrong yet, is there a specific part of that post that I'm guilty of violating? – JoshG Feb 06 '12 at 05:38
  • 4
    Code as shown is legitimate. If you add `main`, a definition of `HookContext` *and nothing else* to these exact 3 one-line files, compile and link, do you still have an error? – n. m. could be an AI Feb 06 '12 at 05:49

2 Answers2

0

I would use some kind of singleton. Gives you the ability to insert some initialization later on or convert it into something else.

library.cpp:

static HookContext g_context;
HookContext& getHookContext()
{
  return g_context;
}

A.cpp:

extern HookContext& getHookContext();
Totonga
  • 4,236
  • 2
  • 25
  • 31
0

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.

JoshG
  • 775
  • 1
  • 7
  • 19