Library linking basics
What you'll learn: How the linker combines your compiled code with pre-written libraries to create a finished executable.
The IKEA analogy
Imagine you are building a desk. You have the wooden boards you cut yourself (your source code), but you also need a bag of specialized screws and a specific hex key to put it all together. You didn’t manufacture the screws; you bought them from a hardware store (a library).
Compiling a C program works the same way. The compiler turns your code into an "object file," which is like your wooden boards—ready to go, but not yet a desk. The Linker is the final step of the process. It takes your object file and "links" it to libraries containing the code for standard functions like printf. Without the linker, your computer wouldn't know where the actual instructions for printf live.
Static vs. Dynamic Linking
There are two main ways the linker gathers these "screws":
- Static Linking: The linker copies the library code directly into your final program file. It’s like welding the screws into the desk. The resulting file is larger, but it’s self-contained and runs anywhere.
- Dynamic Linking: The linker just leaves a note saying, "Look for the screws in this specific drawer when you start the desk up." The program stays small, but it requires the library to be present on the user's computer to run.
What it looks like
When you use a standard library like <math.h>, you tell the compiler to find the math library (often named m) using a specific flag, like -lm.
#include <stdio.h>
#include <math.h>
int main() {
double result = sqrt(16.0);
// The linker finds the code for 'sqrt' in the math library
// and connects it to this call.
printf("The square root is: %f\n", result);
return 0;
}
If you forget to link a library, you will see a "linker error" (often called an undefined reference). This means the compiler understood your code, but the linker couldn't find the actual machinery to make the function work. It’s the difference between having the blueprints for a desk and actually having the parts to build it.
Key takeaway
Linking is the final assembly step where your individual code files are hooked up to external libraries to create a functional, runnable program.