Search code examples
c++cmacrosc-preprocessorcompiler-directives

Which program in the compiler takes care of the preprocessors?


Compiler is a combination of many programs. So which program takes care of which part during compilation? I read somewhere that the preprocessor program takes care of the C preprocessor directives(macros). Is that correct?


Solution

  • There is nothing saying how a compiler should/must be designed internally, so it will be different from compiler to compiler.

    Traditionally however, they are divided into pre-processor, compiler and linker. These may be inside the same executable, or in several.

    The pre-processor does everything that needs to be done before the compiler starts checking the actual language syntax. The compiler is checking if the source is valid C, does it make sense? And then translates the source code into an executable program, which behaves as specified by the C standard.

    Some compilers give the output in the form of a hardware-independent "object file", in which case a linker is needed to translate one or several object files into machine code. But the compiler may as well give the output as machine code, in which case the only task of the linker is to put all different parts (translation units) of the program together, including libraries, and check if all identifiers (variables, functions etc) used by the program are present - if not, you will get a linker error.

    The C standard (C17 5.1.1.2) only speaks of translation phases, which is mostly dictating the order of pre-processing. Roughly, translation phases 1 to 6 are what we would call "pre-processing", step 7 is "compiling", and step 8 is "linking".