How are extern variables defined?

This question already has an answer here:

  • What is the difference between a definition and a declaration? 25 answers
  • How do I use extern to share variables between source files? 15 answers

  • extern int i
    

    ...is a variable declaration, since it only tells the compiler "there exists a variable called i , but it's defined somewhere else".

    int i
    

    ...is a variable definition, since it tells the compiler to create the actual variable.


    The keyword extern is used to declare external variables, so the book is right.

    There is one exception, if an initializer is added, then it's a definition:

    extern int i = 42;
    

    declaration : variable just declared

    Ex: int i; 
    

    definition : variable declaration+its initialization with value.

    Ex: int i=10;
    

    In your case

    extern int i;// is a declaration    
    //because you did not initialize value to i here.
    

    Assuming j is Global variable. then it is initialized with ZERO at the time of declaration.
    Here declaration+initialization =definition

    int j; //definition  
    

    if j is local then it is declaration only.

    链接地址: http://www.djcxy.com/p/40632.html

    上一篇: 声明和定义

    下一篇: extern变量是如何定义的?