Using const in header-file

c++, constants, header

Solution

By default, variables declared `const` have internal linkage, as if they were also declared `static`. If you include the header, then the `extern` declaration will give it external linkage and all will be fine. Otherwise, the definition isn't available from other translation units.

You could avoid including the header by adding `extern` to the definition; but it's better to include the header anyway so the compiler can check that the two declarations are compatible.

Better still might be to define it with internal linkage in the header,

const int ONE = 1;

with no definition in the source file; then its value is available as a constant expression.

Problem

in file.h: ``` extern const int ONE; ``` in file.cpp ``` #include "file.h" const int ONE = 1; ``` and in main.cpp ``` #include <iostream> #include "file.h" int main() { std::cout << ONE << std::endl; } ``` The question: Why must i use `#include "file.h"` in file.cpp? There is a definition of `ONE`. Thanks

Original source