Take for example I have two source file func.cpp and main.cpp. func.cpp contain definitions of 10 functions. Have a corresponding header file for func.cpp included in main.cpp. Now compiler will compile both the source files individually in object files func.o and main.o. Now comes the linker. How does the linker know that main.cpp is my main file and has some functions that are called from other files and they need to be resolved? Means why it won't convert the func.o in final executable which has no function references that need be resolved. On the other hand main.o which is using only one function from func.o gets converted to an executable by resolving that one reference. Also will the final executable include the object code corresponding to the rest of 9 functions that are not called in main.cpp?
-
Why do you think the linker needs to know in which of all the applied input files `main()` was implemented? Just make sure you have one, and it is seen by the linker in the right oder. – Jan 27 '18 at 18:02
-
Try what happens when you put a main in both files. – Jan 27 '18 at 18:20
-
@manni66 At least what will be present in final executable. All the 10 functions or just that one that has been called in main? – hardik2 Jan 27 '18 at 18:26
-
Try nm on linux or dumpbin on windows. – Jan 27 '18 at 18:29
1 Answers
How does the linker know that main.cpp is my main file and has some functions that are called from other files and they need to be resolved?
The linker doesn't really care which file has main()
, it will simply look to see that there is one (and only one) main()
across all of the object files.
Means why it won't convert the func.o in final executable which has no function references that need be resolved. On the other hand main.o which is using only one function from func.o gets converted to an executable by resolving that one reference.
The linker doesn't convert any individual object file to an executable; it links up all of the object files into a single executable.
Also will the final executable include the object code corresponding to the rest of 9 functions that are not called in main.cpp?
It depends. See this post for a detailed explanation.

- 140
- 7