How to compile C/C++ files with an external library

Introduction

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:

main.c

#include "lib.h"

int main() {
    fct();
}

lib/lib.h

#include <stdio.h>

void fct();

lib/lib.c

#include "lib.h"

void fct() {
    printf("This is printed from a function in an external library\n");
}

Command line compilation

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"

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$

See also


Last update : 06/14/2023