Header search paths
What you'll learn: How to tell the compiler exactly where to look for your custom header files when they aren't in the same folder as your code.
The library analogy
Imagine you are writing a research paper. If a reference book is sitting right on your desk, you can grab it instantly. This is like putting a .h file in the same folder as your .c file; you simply write #include "my_header.h" and the compiler finds it.
However, if that book is in the "Science" wing of a massive university library, you need a map. A header search path is that map. It tells the compiler: "If you don't see the file on my desk, go look in this specific shelf in the library." Without this path, the compiler gives up and throws a "No such file or directory" error.
The -I flag
In the real world, professional projects are organized into folders. You might have a src folder for your code and an include folder for your headers. To bridge that gap, we use a compiler flag: -I (that’s a capital i for "Include").
When you run your compiler, you append the path to your headers. If your headers are in a folder named secret_stuff, your command looks like this:
gcc main.c -I ./secret_stuff -o my_program
The compiler now has two places to look: the current directory and the secret_stuff directory.
Angle brackets vs. Quotes
You may have noticed C uses two ways to include files:
#include <stdio.h>: The angle brackets tell the compiler to look in System Paths (the "Standard Library" section of the library).#include "my_settings.h": The quotes tell the compiler to look in Local Paths (your desk) first, and then check any paths you provided with the-Iflag.
By using search paths, you keep your project tidy. You can move your headers to a dedicated folder and simply update your build command, rather than cluttering your source code folder with hundreds of files.
Key takeaway
Use the -I flag during compilation to point the compiler toward folders containing your header files.