Search code examples
c++linkercompiler-construction

Does linker link an object file with itself?


From what I read in other SO answers, like this and this, compiler converts the source code into object file. And the object files might contain references to functions like printf that needs to be resolved by the linker.

What I don't understand is, when both declaration and definition exist in the same file, like the following case, does compiler or linker resolve the reference to return1?

Or is this just a part of the compiler optimization?

int return1();

int return2() {
  int b = return1();
  return b + 1;
}

int return1() {
  return 1;
}

int main() {
  int b = return2();
}

I have ensured that preprocessing has nothing to do with this by running g++ -E main.cpp.


Update 2020-7-22

The answers are all helpful! Thanks!

From the answers below, it seems to me that the compiler may or may not resolve the reference to return1. However, I'm still unclear if there's only one translation unit, like the example I gave, and if compiler did not resolve it, does this mean that linker must resolve it then?

Since it seems to me that linker will link several (greater than one) object files together, and if there's only one translation unit (object file), linker need to link the object file with itself, am I right?

And is there anyway to know for sure which one is the case on my computer?


Solution

  • It depends. Both options are possible, so are options that you didn't mention, like either the compiler or the linker rearranging the code so that none of the functions exist any more. It's fine thinking about compilers emitting references to functions and linkers resolving those references as a way of understanding C++, but bear in mind is that all the compiler and linker have to do is produce a working program and there are many different ways to do that.

    One thing the compiler and linker must do however, is make sure that any calls to standard library functions happen (like printf as you mentioned), and happen in the order that the C++ source specifies. Apart from that (and some other similar concerns) they can more or less do as they wish.