6

I'm new to c++ and have been learning how to create a makefile and have noticed that one of the examples I have (which has to do with 'updating' changed files, and ignoring unchanged files) has the following command:

# sysCompiler is set to g++
.o:.cpp 
    $(sysCompiler) -c $<

According to the manual for g++, this compiles or assembles the source files but doesn't link them.

> -c Compile or assemble the source files, but do not link. The linking stage simply is not done. The ultimate output is in the form of an object file for each source file. By default, the object file name for a source file is made by replacing the suffix .c',.i', .s', etc., with.o'. Unrecognized input files, not requiring compilation or assembly, are ignored.

In other words, am just wondering what exactly 'not linking' means when it comes to compiling in c++?

backslash
  • 304
  • 4
  • 9

1 Answers1

9

The code of a single C or C++ program may be split among multiple C or C++ files. These files are called translation units.

Compiling transforms each translation unit to a special format representing the binary code that belongs to a single translation unit, along with some additional information to connect multiple units together.

For example, one could define a function in one a.c file, and call it from b.c file. The format places the binary code of the function into a.o, and also records at what location the code of the function starts. File b.c records all references to the function into b.o.

Linking connects references from b.o to the function from a.o, producing the final executable of the program.

Splitting translation process into two stages, compilation and linking, is done to improve translation speed. When you modify a single file form a set of a dozen of files or so, only that one file needs to be compiled, while the remaining .o files could be reused form previous translation.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523