How does extern work in c++?

不打扰是莪最后的温柔 提交于 2019-12-01 05:22:40

extern is used to refer to a variable defined in a different compilation unit (for now, you can think of a compilation unit as a .cpp file). The statements in your example declare rather than define cin and cout. It is telling the compiler that the definition of these objects is found in another compilation unit (where they are not declared as extern).

extern means "these variables are defined in some other compilation unit (.cpp or .lib file)"

In this case, you #include <iostream> into your .cpp file, and because cin and cout are declared as extern, the compiler will let you use them without complaining. Then, when the linker runs, it looks up all of the extern variables and sorts it all out.

No, this is an explicit way to say cin and cout are declared without actually defining them.

The extern keyword tells the compiler that a variable is declared in another source(i.e outside the current scope). The linker then finds this actual declaration and sets up the extern variable to point to the correct location.

variables declared by extern statements will not have any space allocated for them, as they should be properly defined elsewhere. If a variable is declared extern, and the linker finds no actual declaration of it, it will show error.

Eg. extern int i;

//this declares that there is a variable named i of type int, defined somewhere in the program.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!