Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

c++ - Using "extern" keyword without #include "file.h"

Right now i read Stephen Prata's book about C++, and learning about extern keyword and its usage. So i have a question. Can i type "extern int var a;" without including a file that defines and initializes this 'a' variable?

#include <iostream>
//#include "vars.h" Not including the file with 'a' variable

using namespace std;

extern int a;

int main()
{   
    cout << a << endl;

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The extern keyword will denote that the variable has external linkage.

When a name has external linkage, the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.

From https://eel.is/c++draft/basic.link

If you attempt to run the above code as is, you will get a linker error as a is not defined in the current scope. So it will have to get it from another translation unit, which can be done during the linking process.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...