The C++ Build Process


C++ build process

Building an executable file from a C++ source code file is a multi-step process. For example, if you have a C++ source code file named prog1.cpp and you execute the command

   g++ -Wall -Werror -ansi -pedantic -std=c++14 -o prog1 prog1.cpp

the build process looks like this:

  1. The C++ preprocessor copies the contents of the included header files into the source code file, generates macro code, and replaces symbolic constants defined using #define with their values.

  2. The expanded source code file produced by the C++ preprocessor is compiled into the assembly language for the platform.

  3. The assembler code generated by the compiler is assembled into the object code for the platform.

  4. The object code file generated by the assembler combined with functions from the standard library archive files by the linker to produce an executable file. By default, this executable file is named a.out. In this case, we have used the -o option to specify the name of the executable file as prog1.

By using appropriate compiler options, we can stop this process at any stage.

  1. To stop the process after the preprocessor step, you can use the -E option:

        g++ -Wall -Werror -ansi -pedantic -std=c++14 -E prog1.cpp
    

    The expanded source code file will be printed on standard output (the screen by default); you can redirect the output to a file if you wish. Note that the expanded source code file is often incredibly large - a 20 line source code file can easily produce an expanded file of 20,000 lines or more, depending on which header files were included.

  2. To stop the process after the compile step, you can use the -S option:

        g++ -Wall -Werror -ansi -pedantic -std=c++14 -S prog1.cpp
    

    By default, the assembler code for a source file named filename.cpp will be placed in a file named filename.s.

  3. To stop the process after the assembly step, you can use the -c option:

        g++ -Wall -Werror -ansi -pedantic -std=c++14 -c prog1.cpp
    

    By default, the object code for a source file named filename.cpp will be placed in a file named filename.o.

Projects with Multiple Source Files

For a project with multiple source files, Steps 1 through 3 of the build process are performed independently on each source file to produce an object file. The linker then collects the object files and does the following:

The key thing to understand here is that each source file is an independent translation unit. That means any required #include statements, using statements, class definitions, function prototypes, etc. neeed to be present in each source file. A using statement coded in one source file is not automatically available to your other source files.