This page explains how to compile a C project with an external library in command line.
In the following, we take the example of three files, a main.c
and a library composed of two files lib.c
and lib.h
:
project
|- main.c
|- lib
| |-lib.c
| |-lib.h
Note that this example are based on .c files, but it also works with cpp object oriented files.
Here are the source files:
#include "lib.h"
int main() {
fct();
}
#include <stdio.h>
void fct();
#include "lib.h"
void fct() {
printf("This is printed from a function in an external library\n");
}
Assuming you are in the root folder of the project, the following line compile the entire project:
g++ -o output.exe "main.c" "lib/lib.c" -I "lib"
-o
specifies the output file (i.e. the executable file, here output.exe
)"main.c"
and "lib/lib.c"
are the source files-I
specifies the path of the header files (.h
) Here is the result:
fifi@~/project$ g++ -o output.exe "main.c" "lib/lib.c" -I "lib"
fifi@~/project$ ./output.exe
This is printed from a function in an external library
fifi@~/project$