Library Linking
in C++
Understand how include paths and link flags connect your code to external libraries: the essential bridge between writing code and building programs.
What Is a Library?
A library is a collection of pre-written, pre-compiled code that you can reuse in your own programs. Instead of writing everything from scratch, you link against a library to borrow its functionality.
The Two-Phase Build Process
Building a C++ program happens in two distinct phases. Understanding these phases is the key to understanding library linking.
Why Does Linking Matter?
Without linking, the compiler can check your code's syntax but it has no idea where to find the actual machine code for library functions. This creates the dreaded "undefined reference" error.
Include Paths: -I Flag
The include path tells the compiler where to search for header files when your code uses #include. By default it only knows about system headers.
Link Flags: -L and -l
Link flags tell the linker where to find compiled library files and which libraries to use. There are two flags that work together:
The Naming Convention
Library filenames follow a pattern. The -l flag maps to a filename by adding lib as a prefix:
Static vs Dynamic Libraries
| Static (.a / .lib) | Dynamic (.so / .dll) | |
|---|---|---|
| When linked | At compile time | At run time |
| Bundled into exe? | Yes: code is copied in | No: loaded from disk |
| File size | Larger executable | Smaller executable |
| Portability | Self-contained | Needs .so/.dll present |
| Updates | Must recompile | Swap the .so/.dll |
Step-by-Step: Linking a Library
Example 1: Simple Math Library
Link against the standard math library libm to use functions like sqrt() and sin().
Example 2: SFML Graphics
SFML is installed in a non-standard location. You need both include and link flags.
Example 3: All-in-One Command
In practice, you can compile and link in a single g++ call. The compiler runs both phases for you.
The Full Picture
Common Mistakes
Summary of Flags
| Flag | Phase | Purpose | Example |
|---|---|---|---|
| -I | Compilation | Add header search path | -I/opt/sfml/include |
| -L | Linking | Add library search path | -L/opt/sfml/lib |
| -l | Linking | Name the library to link | -lsfml-graphics |
| -c | Compilation | Compile only (no linking) | -c main.cpp |
| -o | Output | Name the output file | -o myprogram |
Question 1 of 5
What does the -I flag tell the compiler to do?
Question 2 of 5
A library file is named libboost_filesystem.so. What is the correct -l flag to link it?
Question 3 of 5
You see the error: "undefined reference to `sf::RenderWindow::RenderWindow(...)`". Which flag is most likely missing?
Question 4 of 5
What is the difference between -L and -l?
Question 5 of 5
Which of the following commands correctly compiles main.cpp with a library installed at /home/user/mylib?