HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

How does the linker know where to look for a function implementation in C++?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
linkertheknowwherelookfunctionfordoeshowimplementation

Problem

I am currently learning about how the compilation and linking works in C++. I think I kinda get how the compiler works, and that for a file to fully compile you don't need to have function implementations, but only declarations. It is the linker's job to link the function declaration to its implementation.

But now I have this weird question, for example if I have a .cpp file in which I am using 1000 different functions, and each of those functions has its own separate .cpp and .h file, how does the linker know which of the cpp files to scan to find that specific function? I mean does the linker know where the function is located or does the linker every time for every function scan the whole project to find that specific function?

Solution

The linker is given explicitly the list of files to use, in the command line of the linker. They can be object files (.obj / .o) - compiled code - or libraries (.lib / .a) - object files structured in a single one.

Part of the job of the linker is to establish a list of the available functions and assign them an address in memory. This is enough to generate the calls where needed.

Note that the linker does not see the source code itself.

Context

StackExchange Computer Science Q#157125, answer score: 13

Revisions (0)

No revisions yet.