C Language Header File Inclusion Path Resolution: Where Does the Compiler Look for Files?

In practical development, one often encounters the following question:

#include "imx6ul.h"

Clearly, this header file is not in the directory of the current <span>.c</span> file, yet the compilation passes smoothly. Why is this? This article will explain the header file search rules in C language for <span>#include</span>.

📌 1. Two Forms of <span>#include</span>

  • <span>#include "filename"</span>
  • <span>#include <filename></span>

🔍 2. Order of Header File Search Paths

#include “filename”

  1. Current source file directory
  2. <span>-I</span> specified directories
  3. System default directories

#include <filename>

  1. <span>-I</span> specified directories
  2. System default directories

✅ 3. Why Can Projects Compile Successfully?

Many projects add similar lines in the Makefile:

-I imx6ul -I bsp/clk -I bsp/led -I bsp/delay

This allows the compiler to search for header files in the specified directories, even if they are not in the current directory.

📎 4. Is Relative Path Inclusion Feasible?

#include "../imx6ul/imx6ul.h"

While feasible, it is not recommended for the following reasons:

  • Paths may become invalid if they change
  • Poor readability
  • High maintenance cost

📘 5. Summary Table of Search Rules

Form Search Path
#include “xxx.h” Current directory → -I → System directory
#include <xxx.h> -I → System directory
Relative path inclusion Search by path, prone to errors, not recommended

🖼️ 6. Illustrated Explanation

📌 Recommendations

  • Consistently use <span>#include "xxx.h"</span>
  • Specify paths through Makefile/compiler settings with <span>-I</span>
  • Avoid using hard-coded relative paths

Leave a Comment