Search code examples
c++visual-c++linkeride

How the linker find the correct library?


I know what preprocessing is, how compiler works, and how linker links the object files.

But what I still haven't been able to answer is:

In an IDE like VS

suppose we have a library called DariushTest.o that implemented a function called print() and have a header file called test.h and we have other libraries that implemented the print() function but we don't include their header files in our code. Suppose we include the test.h header in our code and we use the print() function in our main function.

NOW! if there are several libraries that have implemented this function:

  • After compiling the code, how does the linker find out which library this code is related to and with which file should it link?

The reason that I ask this question is that the header file doesn't connect to DariushTest.o file and the compiler doesn't care about it.

So how does the linker link the print() function from DariushTest.o and not from other libraries? How does the linker find the correct library?


Solution

  • So how linker links the print() function from DariushTest.o not from other libraries?

    It doesn't. If you break the ODR by having the same function name in 2 different compilation units, then the behavior of the program is undefined. The linker might notice and diagnose the redefinition and might not.