C++ extern keyword on functions. Why no just include the header file?

If I understand it correctly this means

extern void foo();

that the function foo is declared in another translation unit.

1) Why not just #include the header in which this function is declared?

2) How does the linker know where to look for function at linking time?

edit: Maybe I should clarify that the above declaration is then followed by using the function

foo();

It is never defined in this translation unit.


Solution 1:

1) It may not have a header file. But yes, in general, for large projects, you should have a header file if multiple translation units are going to use that function (don't repeat yourself).

2) The linker searches through all the object files and libraries it was told about to find functions and other symbols.

Solution 2:

No, this means that function foo is declared with external linkage. External linkage means that name foo refers to the same function in the entire program. Where the function is defined does not matter. It can be defined in this translation unit. It can be defined in other translation unit.

Using extern keyword as shown in your example is superfluous. Functions always have external linkage by default. The above is 100% equivalent to just

void foo();

As for the linker, when the linker links the program together it simply looks everywhere. It looks through all definitions until it finds the definition for foo.

Solution 3:

As others have already stated, the extern keyword is used to state the name (a variable or function) has external linkage, meaning the name refers to the same object in the entire program. Also, this is the default for variables and functions defined at the file scope, so this usage is superfluous.

There's another use of the extern keyword that goes like this:

extern "C" void foo();

This means the function foo will be linked using the C conventions for linkage (maybe because this is a function defined in a C library or is a function intended to be called by C programs).