AFAIK, any declaration of a variable or a function in file scope has external linkage by default. static mean “it has internal linkage”, extern — “it maybe defined elsewhere”, not “it has external linkage”.
If so, why we need extern keyword? In other words, what is difference between int foo; and extern int foo; (file scope)?
The
externkeyword 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:
If you keep this declaration by itself and then use
xyzin your code, you would trigger an “undefined symbol” error during the linking phase.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
externin the header, and not use extern in exactly one C or C++ file.