Sibirski Tiger Sibirski Tiger - 5 months ago 24
C++ Question

How does C++ linker know what .cpp files to use

I am a C++ learner and I came across a concept of separating code into multiple files to speed up compiling process on bigger projects.

However what the book doesn't tell me and I have tried to find it in other books and on the web, but with no luck is how does linker (during compilation) knows what files to include.

When I make new file I connect its header to the main file with

#include "newfile.h"
, however in this header I don't write where to find definitions of functions.

So how I imagine the process is that it starts in the main file and there it finds "connections" to other files. The question is how it finds those .cpp files that as far as I see don't need to be named the same as its header file.


Main file:

#include <iostream>
#include "krneki_H.h"

using namespace std;

int main()

And header file:

void krneki1();
void krneki2();
void krneki3();

And new .cpp file:

#include <iostream>
#include "krneki_H.h"

using namespace std;

void krneki1() {

void krneki2() {

void krneki3() {

Notice that there is no indication to use second cpp file. It just knows to use it. Does it search all .cpp files in the map?

Thank you for answer.


No. It doesn't just know to use it. In your example, if you compile with main.cpp and without that new cpp file, you'll get an "undefined reference" error.

What happens is that you're using a fancy IDE that automatically compiles all cpp files. It includes them all by default in your makefile.

I recommend that you try to design a makefile from scratch, and see for yourself how you'll get that "undefined reference" error if you don't include the cpp file that has the implementations of your functions.