0

When compiling C source files, we include header files for example using #include "myheader.h".

The pre-processor will expand this header file before compiling the file. However, how does it find this header file exactly? I believe, the path of the header files is passed as an argument to the linker using -I for example to gcc.

I always thought that the linker only runs after compilation. So does the linker actually run before, to find stuff such as header files, and after compilation to combine various object files etc. ? Thanks

Engineer999
  • 3,683
  • 6
  • 33
  • 71
  • 2
    The `-I` (upper-case i) option to a front-end program like `gcc` is passed to the preprocessor, not the linker. – Some programmer dude Dec 09 '19 at 14:35
  • In the ordinary course of events, in C, the linker does nothing with header files. It handles object files and libraries — shared and static. However, with a command line such as `gcc -o program -I/home/project/include source.c -L/home/project/lib -lproject`, the compilation uses the preprocessor (on `source.c`), the compiler proper, and the linker, all in a single command-line invocation. – Jonathan Leffler Dec 09 '19 at 14:36
  • 1
    The linker doesn't care at all about header files nor about .c files – Jabberwocky Dec 09 '19 at 15:43

2 Answers2

0

Headers mostly declare meta symbols, and function prototypes that allow the compiler to match/check cross compilation unit calling of functions.

All actual symbols interesting to a linker are defined in C files. The compiler can use preprocessor symbols (#defines) during codegeneration, but they are then inlined in the generated code.

Likewise, in the case of C++ inline methods or templates, code is generated by the compiler on the place where they are used.

This means the linker does not need anything from the headers, anything that would be needed is already processed by the compiler into the generated code stream (to the assembler or object file compiler output).

So no, includefiles are not relevant to the linker.

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89
0

Below a stripped down version of the way from sources to executables.

+-------------------------------+
| sources (typical .c/.h files) |
+-------------------------------+
               |
               V
         pre-processor
               |
               V
+-------------------------------+
|     intermediate sources      |
+-------------------------------+
               |
               V
           compiler
               |
               V
+-------------------------------+
|       object files (.o)       |
+-------------------------------+
               |
               V
            linker
               |
               V
+-------------------------------+
| executables/shared libraries  |
+-------------------------------+
alk
  • 69,737
  • 10
  • 105
  • 255