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

user199421 picture user199421 · Apr 9, 2010 · Viewed 60.3k times · Source

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.

Answer

Brian Neal picture Brian Neal · Apr 9, 2010

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.