Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using const in header-file

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

like image 720
Simankov Avatar asked Dec 26 '22 14:12

Simankov


2 Answers

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.

like image 105
Mike Seymour Avatar answered Jan 14 '23 14:01

Mike Seymour


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.

like image 33
Konrad Rudolph Avatar answered Jan 14 '23 14:01

Konrad Rudolph