Why does declaring an extern variable inside main() works,but not defining it inside main() as well?

后端 未结 4 1330
悲哀的现实
悲哀的现实 2021-01-14 04:29

This seems very trivial but a somewhat rigorous explanation for the following behavior will help my understanding of extern a lot.So I\'ll appreciate your answe

相关标签:
4条回答
  • 2021-01-14 04:58

    just remember the concept that when we declare a variable as extern inside a function we can only define it outside of that function.

    0 讨论(0)
  • 2021-01-14 05:04

    Nobody uses extern in this way. extern is usually used on big projects, lots of .c , .h files and some variables needs to be shared. On those circumstances, compilation often fails to resolve variable declaration (perhaps, it's on some .h file which yet to compile), then "extern" is used to tell compilar to leave it for now and proceed compilation, this thing will be dealt at linking phase.

    0 讨论(0)
  • 2021-01-14 05:05

    extern variable declaration is a promise to the compiler that there would be a definition of a global variable some place else. Local variables do not qualify as fulfillments of the promise to the compiler, because they are invisible to linkers. In a sense, extern declarations are similar to forward declarations of functions: you say to the compiler "I know this function is there, so let me use it now, and let linker take care of locating the actual implementation".

    0 讨论(0)
  • 2021-01-14 05:13
    Why are we allowed to declare an extern variable inside a function,without any warning or error?If valid,what exactly does it mean?
    

    Ans:- we can use extern at functional level, to expose it only during the scope of that function.

    Since we declared x as extern inside the function and it showed no error,why then this declaration doesn't link to the definition of the variable inside the function,but looks outside,when the variable is defined outside? Is conflicting storage-class declaration auto-vs-extern the reason for this?
    

    Ans:Variables declared at block scope (i.e. local variables) have no linkage, unless they are explicitly decalred as extern.

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