0

Usually when declaring a const of any sort you're supposed to assign a value to it immediately, but not in header files? why?

Shalom Craimer
  • 20,659
  • 8
  • 70
  • 106
samsas
  • 17
  • 1
  • You're not supposed to make variables in header files at all (normal, global ones) – deviantfan Jun 04 '17 at 22:15
  • 1
    @deviantfan That's simply not true. Things like `const int MEANING = 42;` are perfectly OK in header files. –  Jun 04 '17 at 22:17
  • @NeilButterworth If you're ok with linker errors after including it multiple times...? edit: "normal" – deviantfan Jun 04 '17 at 22:18
  • @deviant You won't get any linker errors. https://stackoverflow.com/questions/998425/why-does-const-imply-internal-linkage-in-c-when-it-doesnt-in-c –  Jun 04 '17 at 22:22
  • @samsas Post some code that illustrates what you are asking about. –  Jun 04 '17 at 22:23
  • @NeilButterworth 3th time: "normal". WIthout any specifier. – deviantfan Jun 04 '17 at 22:27
  • @deviant Your personal definition of the word "normal", I suppose? –  Jun 04 '17 at 22:28
  • Related: https://stackoverflow.com/questions/1358400/what-is-external-linkage-and-internal-linkage – Weak to Enuma Elish Jun 04 '17 at 22:39
  • @NeilButterworth Then what should I call it? "Variable without extern without const without constexpr without static without inline without..."? Sigh... – deviantfan Jun 04 '17 at 22:49
  • @deviantfan -- `const int MEANING = 42;` defines `MEANING` with **internal** linkage (because of the `const`),, so there is no problem putting it in a header file. – Pete Becker Jun 05 '17 at 02:59

2 Answers2

6

It's because you declared it extern, extern tells the compiler that the definition and declaration of the variable are in another file and you are simply making your code "aware" of the existence of that variable, as such the compiler does not expect any assignment on the header.

Makogan
  • 8,208
  • 7
  • 44
  • 112
2

Remember not only you don't need to, but you shouldn't assign a value to extern declarations because that makes them a definition.

amin
  • 3,672
  • 5
  • 33
  • 61