C++ Development Tutorial 2: Compile Multiple Files (1) — Compiling Process Basics

In the last tutorial, we compiled a simple single source file C++ program. However, most programs consist of multiple source files. It’s also good practice to separate source code into multiple files for better organization. From now on, we are starting to handle multiple file compilation and all the common pitfalls around it.

  1. Compilation.
  2. Linking.

1. Preprocessing

During preprocessing, the preprocessor will deal with file inclusion that looks like

#include <name>
#include “name” 

2. Compilation

In the second step, the source file with its included header files will be translated to an object file. An object file is a file containing relocatable format machine code which means it can be later used together with other object files (relocatable). You can use “g++ -c ” to perform preprocessing + compiling in one step.

Definition vs Declaration

A declaration needs to contain the name and type of the entity. A definition provides all details it needs to construct/use such an entity. For example, a function definition should contain its body, a class definition needs to provide all member functions and variables. Definition can be provided together with the declaration.

C++ requires all symbols to be declared at the moment they are used/referenced in source code.

This is also true in almost every programming language because it can help the compiler identify what the symbol is and does not have to search through every possible place. Particularly in C++, the declaration must appear 1. in the same source file before its usage or 2. in other files and included in the same source before its usage. The second part shouldn’t be surprising to you if you read the preprocessing part.

3. Linking

Linking is the process of generating executables from multiple object files. During linking, all symbols must find their definition. Otherwise, the linker will complain and issue an error.

One Definition Rule

This rule is commonly referred to as ODR (one definition rule) in C++ standard:

Any unit, template, type, function, or object can have no more than one definition in the program.

The first thing you notice is it didn’t mention declarations at all. Yes, a symbol can be declared several times!

4. Summary

In this tutorial, we start to compile multiple source files using g++.

  1. Compiling translates preprocessed source files into object files.
  2. Linking links all objects files together to generate an executable.

References

[1] Compiling and Linking

Building Compilers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store