Course contentsShow
← C
Lesson 815 of 1,21911. The Preprocessor and BuildFree lesson

Linking with shared libraries `-l` and `-L`

Linking with shared libraries -l and -L

What you'll learn: How to tell the compiler which external libraries your program needs and where to find them on your computer.

When you use functions from an external library—like a physics engine or a graphics tool—your compiler needs help finding the actual code for those functions. Think of your code as a recipe that calls for a "pre-made sauce." The compiler knows what the sauce is, but it doesn't know which shelf in the pantry it's sitting on or which specific brand to use. We use two flags, -l and -L, to point the way.

The -l flag: Naming the library

The lowercase -l flag stands for link. This tells the compiler the specific name of the library you want to use.

There is a small trick here: by convention, shared library files start with lib and end with .so (on Linux) or .dylib (on macOS). When using the -l flag, you drop the lib prefix and the extension. For example, to link a library file named libmathhelper.so, you simply write -lmathhelper.

The -L flag: Locating the library

The uppercase -L flag stands for Look in this directory. By default, the compiler only looks in standard system folders (like /usr/lib). If your library is sitting in a custom folder or a subfolder of your project, the compiler will get lost.

The -L flag tells the compiler: "Before you give up, check this specific folder too."

Putting it together

Imagine you have a project where your library is stored in a folder named /libs and the file is named libphysics.so. Your compilation command would look like this:

gcc main.c -o my_program -L./libs -lphysics

In this command:

  1. gcc main.c -o my_program: Compiles your source code.
  2. -L./libs: Adds the "libs" folder to the search path.
  3. -lphysics: Searches for a file named libphysics.so (or .dylib) inside those paths and links it.

If you forget -L, the compiler will say "library not found." If you forget -l, the compiler will complain about "undefined references" because it saw the function calls in your code but didn't know which library provided the instructions to execute them.

Key takeaway

Use -L to specify the folder path and -l to specify the library name (minus the 'lib' prefix).