Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Exmple:

Main file:

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

using namespace std;


int main()
{
 krneki1();
 krneki2();
 krneki3();
}

And header file:

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

And new .cpp file:

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

using namespace std;

void krneki1() {
cout<<"Krneki1"<<endl;}

void krneki2() {
cout<<"Krneki2"<<endl;}

void krneki3() {
cout<<"Krneki3"<<endl;}

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.

like image 772
Sibirski Tiger Avatar asked Feb 06 '23 21:02

Sibirski Tiger


2 Answers

You compile both .cpp files using gcc -c or a similar command line, and then pass both of the .o files produced to the linker. The linker does not magically figure out that you want to compile another .cpp file.

For example

gcc -c main.cpp -o main.o           # compile
gcc -c krneki_H.cpp -o krneki_H.o   # compile
gcc main.o krneki_H.o -o main       # link

Your IDE may take care of these details automatically, in which case it compiles all .cpp files you added to your project, then links all the .o files produced by the compilation step.

like image 70
Brian Bi Avatar answered Feb 08 '23 12:02

Brian Bi


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.

like image 45
The Quantum Physicist Avatar answered Feb 08 '23 10:02

The Quantum Physicist