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

Categories

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...