Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between 'compiling and linking' and just 'compiling' (with g++)?

Tags:

c++

makefile

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++?

like image 800
backslash Avatar asked Sep 10 '17 18:09

backslash


People also ask

What is the difference between compiling and linking?

Compiling - The modified source code is compiled into binary object code. This code is not yet executable. Linking - The object code is combined with required supporting code to make an executable program. This step typically involves adding in any libraries that are required.

What is the difference between linker and compiler?

A compiler generates object code files (machine language) from source code. A linker combines these object code files into an executable.

What is compilation and linking process?

Compilation: the compiler takes the pre-processor's output and produces an object file from it. Linking: the linker takes the object files produced by the compiler and produces either a library or an executable file.


1 Answers

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.

like image 68
Sergey Kalinichenko Avatar answered Oct 29 '22 19:10

Sergey Kalinichenko