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.
All variables and functions in header files should be extern. Separate header files should be used for variables and functions. Use a C code file to declare the variables and functions and use this in end user code. Extern must be used instead of using global variables.
the extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit. When extern is used with a variable, it's only declared, not defined.
The file that contains the function declaration/implementation does not include the header file with the extern keyword. The file that calls the function does include the header file with the extern keyword, and that's a good thing.
C language has numerous libraries that include predefined functions to make programming easier. In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With