Thank Disch a lot for your reply. However, both the examples are tested and working. Maybe the advance in C++ standard allows such usage. At the end of the message is the sample code that can be compiled with Dev-C++ and the executable can generate the expected results.
To my understanding, the use of "extern" in its definition (i.e., in file1.cpp) is to tells compiler that the variable has external linkage so that its references in other source files can correctly link to it. Otherwise, this global variable would have only internal linkage and compiler could find its definition upon compiling its references in other files.
This type of usage of "extern" is backed in the book "c++ primer (5th edition)" (for details, please refer to Section 2.4 or below)
Quoted from Section 2.4 of the book "c++ primer (5th edition)"
++++++++++++++++++++++++++++
To define a single instance of a const variable, we use the keyword extern on
both its definition and declaration(s):
Click here to view code image
// file_1.cc defines and initializes a const that is accessible to other files
extern const int bufSize = fcn();
// file_1.h
extern const int bufSize; // same bufSize as defined in file_1.cc
++++++++++++++++++++++++++++
Sample source code
file1.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
const char *pstr = "hello";
extern const int ca = 100;
void print();
int main()
{
cout << pstr << endl;
cout << ca << endl;
print();
return 0;
}
|
file2.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
extern const char *pstr;
extern const int ca;
void print()
{
cout << pstr << endl;
cout << ca << endl;
}
|
The above code can be compiled in IDE Dev-C++ with TDM-GCC 4.8.1 64-bit Release as well as options "-static-libgcc -std=gnu++11" and below is the output.
==== output ====
hello
100
hello
100
Just node that the above code is for illustration purposes and it is highly appreciated if any inappropriate use could be pointed out.