I have a problem with an extern variable and an array declaration with it. How to declare an array with global variable which located not in the declarable file.
file1.cpp
const int size = 10;
mainfile.cpp
extern const int size;
void main()
{
int mas[size];
}
int mas[size];
This line has an issue. Please any guess??
First of all constants have internal linkage. Thus these declarations
file1.cpp
const int size = 10;
and
mainfile.cpp
extern const int size;
refer to different entities.
The constant declared in file1.cpp is not visible outside its corresponding compilation unit.
According to the C++ Standard (3.5 Program and linkage)
3 A name having namespace scope (3.3.6) has internal linkage if it is the name of
— a non-volatile variable that is explicitly declared const or constexpr and neither explicitly declared extern nor previously declared to have external linkage; or
In mainfile the value of size is not specified so the compiler will issue an error for statement
int mas[size];
becuase the size of an array shall be a compile-time constant expression.
The simplest solution is to place the constant definition
const int size = 10;
in some common headet file that will be included in each translation unit where there is a reference to the constant.