4

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

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Can you tell more about what you mean when you say "anything that requires its address"?
@alexolut: For example, taking its address with &, or creating a reference to it. Doing these requires it to exist at a well-defined memory location, which requires a definition. Just using its value doesn't, as long as the value is available as a constant expression.
But i can take an address of 'const int i=42' declared in .h-file when I include it in .cpp-file. I tried it on compileonline.com (but there seems to be impossible to give a link to the code).
@alexolut: If you just declare it const, then it's a definition with internal linkage - you can take the address, and you'll get different addresses in each translation unit. If you add extern (so it's just a declaration), then you can't take the address unless there's also a definition somewhere - but you can still use the value.
@alexolut: If, as you say, you particularly want to prevent taking the address, the first. As I said, the second is a definition, so you can take the address of that. But the second is nearly always better, since it can be passed to functions like std::min which take their arguments by reference.
|
3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.