Why do we need the 'extern' keyword in C if file scope declarations have external linkage by default?

前端 未结 4 793
不思量自难忘°
不思量自难忘° 2020-12-14 20:34

AFAIK, any declaration of a variable or a function in file scope has external linkage by default. static mean \"it has internal linkage\",

4条回答
  •  醉酒成梦
    2020-12-14 20:45

    The extern keyword is used primarily for variable declarations. When you forward-declare a function, the keyword is optional.

    The keyword lets the compiler distinguish a forward declaration of a global variable from a definition of a variable:

    extern double xyz; // Declares xyz without defining it
    

    If you keep this declaration by itself and then use xyz in your code, you would trigger an "undefined symbol" error during the linking phase.

    double xyz; // Declares and defines xyz
    

    If you keep this declaration in a header file and use it from several C/C++ files, you would trigger a "multiple definitions" error during the linking phase.

    The solution is to use extern in the header, and not use extern in exactly one C or C++ file.

提交回复
热议问题