How does extern work in c++?

后端 未结 5 1921
温柔的废话
温柔的废话 2021-01-12 10:03

This is from the :

namespace std 
{
  extern istream cin;       ///< Linked to standard input
  extern ostream cout;  
...


        
相关标签:
5条回答
  • 2021-01-12 10:44

    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.

    0 讨论(0)
  • 2021-01-12 10:48

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

    0 讨论(0)
  • 2021-01-12 10:50

    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).

    0 讨论(0)
  • 2021-01-12 10:52

    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.

    0 讨论(0)
  • 2021-01-12 10:52

    Some answers say here that extern means that variable is defined in other compilation unit. Then, following should not compile as no other compilation unit or file is provided to compiler.

    extern int a;
    int main(){
        std::cout<<a<<std::endl;    //Prints 3
    }
    int a=3;
    

    So, I think extern is explicitly used to separate the declaration and definition in case of variable as stated in one of answer. I think it is useless in case of functions.

    0 讨论(0)
提交回复
热议问题