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
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.
There is a definition of ONE.
A definition, yes. But the important thing about including the header file in file.cpp
is that it provides a different declaration of ONE
– namely, one that is marked extern
. This prevents the subsequently defined ONE
constant from having internal linkage and thus not being exported.
In order to make the definition of ONE
, which is in a separate compilation unit, visible to main.cpp
, ONE
’s linkage must not be internal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With