2

In this question I asked why

//foo.h
namespace foo{
    int bar;
}

gave me a linker error when I include foo.h in multiple files. Turns out I need extern int bar; to prevent the error. Why do I need extern? I don't want to type extern before every variable in every namespace that I want access to in multiple translation units. Why doesn't int bar; do what I expected it to? Why does the C++ Standards Committee insist on making me type extern everywhere?

Community
  • 1
  • 1
Michael Dorst
  • 8,210
  • 11
  • 44
  • 71

2 Answers2

10

Extern says that the storage declaration for the variable will be made elsewhere. The linker then goes and looks for the symbol in another file at link time. Without extern you are telling the compiler, allocate some space for a global. If you do this in more than one file the linker will see multiple instances of the same symbol.

CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
  • I see, so basically there are no shortcuts here? I really do have to type `extern` in front of every variable? – Michael Dorst Oct 06 '12 at 20:06
  • It's a little more tricky than that even. You need an extern in front of every variable in the header files, but you need to have a corresponding definition without extern in one of your code files. – CrazyCasta Oct 06 '12 at 20:08
  • And i'll go ahead and say it. if managing global variables by properly extern'ing in declarations becomes a point of being a big pain in the ass, chances are "extern" is not your problem; boatloads of globals sprinkled hither-and-yon *are*. – WhozCraig Oct 06 '12 at 20:50
  • Well that's why they're in namespaces. – Michael Dorst Oct 06 '12 at 22:43
3

Why does the C++ Standards Committee insist on making me type extern everywhere?

It never told to write everywhere ....

namespace foo{
extern "C++" {
    int bar;
    int car;
    int dar;
    int xar;
}

}
perilbrain
  • 7,961
  • 2
  • 27
  • 35