Using const in header file

in the .h file:

 extern const int ONE;

in the .cpp file

#include "file.h"
const int ONE = 1;

and in main.cpp

#include <iostream>
#include "file.h"
int main()
{
    std::cout << ONE << std::endl;
}

Question: Why should I use #include "file.h"in the .cpp file? There is a definition ONE.

thanks

+4
source share
2 answers

By default, variables declared constare internally linked as if they were also declared static. If you include the headline, the ad externwill give it an external link and everything will be okay. Otherwise, the definition is not available from other translation units.

, extern ; , .

,

const int ONE = 1;

; .

+7

ONE.

, . file.cpp , ONE, , extern. ONE , , .

ONE, , main.cpp, ONE, .

+3

Source: https://habr.com/ru/post/1525463/


All Articles