Compiling C/C++ code is quite a big topic, so I would definitely recommend you to also read a tutorial like this: https://www.geeksforgeeks.org/compiling-with-g-plus-plus/, and https://courses.cs.washington.edu/courses/cse373/99au/unix/g++.html.
But anyway:
This is a example project, which uses the library libFoo, and includes several header files from that library:
Myproject:
- Main.cpp
- ClassFoo.cpp
- ClassFoo.hpp
A part of ClassFoo.cpp:
#include "AClassFooHeader.hpp"
ClassFoo::myFunc() {
foo.execute(); // execute a random function in the libFoo library
}
Now let's say we want to compile this project, what command do we need to execute?
So the first part is compiling the project. Basically we will transform the source files into object files. After that we will link them together in a application (together with a library).
Let's say we run this command:
g++ -c Main.cpp ClassFoo.cpp
We will get a include error like: "can't find AClassFooHeader.hpp".
Why is that? Well, the compiler searches on some predefined locations for the header files, but our library is not in a predefined location, so it can't find the header file. How can we solve this?
g++ -I/path/to/lib/folderHeader -c Main.cpp ClassFoo.cpp
So now we included the path to the file, so the compiler knows where to find the AClassFooHeader.hpp
But now we also need to link the objects together in a application. Without a library, this can be done with:
g++ -o application.exe Main.o ClassFoo.o
So we link the .o files in a application (called application.exe)
But now we also need to link our library. This can be done with:
g++ -o application.exe Main.o ClassFoo.o -L/path/to/lib/folderLibrary -lFoo
Where -L is the location where the library is stored, and -l is the name of the library minus lib, so for example libFoo -> -lFoo
This can also be done in a single step:
g++ -o application.exe -I/path/to/lib/folderHeader Main.cpp ClassFoo.cpp -L/path/to/lib/folderLibrary -lFoo