Steps of C++ codes compilation

g++ vs gcc

  • g++ can compile any .c or .cpp files but they will be treated as C++ files only
  • gcc can compile any .c or .cpp files but they will be treated as C and C++ respectively
  • Using g++ to link the object files, files automatically links in the std C++ libraries. gcc does not do this.

Compilation

Suppose we have simplest code in main.cpp file, then

1
2
3
4
5
g++ main.cpp # Produces the executable file (with default name i.e a.out)
./a.out # Runs a.out

g++ main.cpp -o main # Specifies a filename to output rather than default name
./main # Runs main

Not a Single Step Process!

  • Word Compilation is using wrongly.
  • Compilation is just Step 2 of the complete pipeline below.

Compilation Pipline

Barebone Source file

1
2
3
4
5
6
7
#define LUCKY_NUMBER 7

int main()
{
int num = LUCKY_NUMBER;
return 0;
}

Step 1: Preprocessing

g++ -E main.cpp

Outputs:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 1 "main.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "main.cpp"


int main()
{
int num = 7;
return 0;
}

Step 2: Compilation

g++ -S main.cpp

Outputs: main.s

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
	.file	"main.cpp"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
endbr64
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $7, -4(%rbp)
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0"
.section .note.GNU-stack,"",@progbits
.section .note.gnu.property,"a"
.align 8
.long 1f - 0f
.long 4f - 1f
.long 5
0:
.string "GNU"
1:
.align 8
.long 0xc0000002
.long 3f - 2f
2:
.long 0x3
3:
.align 8
4:

Step 3: Assemble

g++ -c main.cpp

Outputs: main.o
It’s a binary file, so we cannot read it.

Step 4: Linking

g++ main.cpp

Outputs: a.out which is executable.

Using Multiple files

Take following 3 files:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// main.cpp
#include <iostream>
#include "add.h"
int main()
{
std::cout << add(2,3) << std::endl;
return 0;
}
// --------------------------------------
// add.h
int add(int, int);
// --------------------------------------
// add.cpp
int add(int x, int y)
{
return x+y;
}
1
2
3
4
5
g++ main.cpp add.cpp -o main # Generates executable file 'main' which outputs 5 when executed

# OR do it in steps
g++ -c main.cpp add.cpp # Genetates two object codes 'main.o' and 'add.o'
g++ main.o add.o -o main # Generates executable file 'main' which outputs 5 when executed