gcc and g++ are both compilers for c++ languages

Example GCC

include <stdio.h>
 
int main() {
    printf("Hello, world!\n");
    return 0;
}

use gcc to compile hello.c

gcc hello.c

Example G++

#include <iostream>
 
int main() {
   std::cout << "Hello, world!" << endl;
   return 0;
}

use g++ to compile hello.cpp

g++ hello.cpp

gcc’s & g++‘s default output executable is called “a.exe” (Windows) or “a.out” (Unixes and Mac OS X)

to run the program

// (Windows) In CMD shell
> a

// (Unixes / Mac OS X) In Bash Shell - include the current path (./)
$ chmod a+x a.out
$ ./a.out

GCC & G++ Breakdown (Preprocessor - Compiler - Assembler - Linker - Executor)

the gcc & g++ compilation of a C/C++ program consists of 4 steps:

preprocessor (cpp): process the directives (#include, #define, etc)

compiler (gcc -S, g++ -S): takes place on the preprocessed files:

  1. checks the C/C++ syntax
  2. converts the C/C++ code into assembly code

assembler (as): converts the assembly code to machine code (binary) as object-files (these object-files can refer to functions that are not defined. Also note these object-files can be used as libraries as well)

linker (ld): produces an executable or a library. It links the object files by replacing the undefined functions with the correct addresses. These functions should be defined in other object-files or in libraries (external object files). There are 2 types of external libraries:

executor: when you launch the executable, the OS will put it in memory. As said earlier, some code isn’t available at this point (i.e. dynamic libraries). But the linker was nice enough to say where to look for it: the executable clearly states which dynamic library the function is defined. The OS will happily open the dynamic library and find the function’s definition

Example - GCC & G++ Breakdown

the command below does the first 4 steps (preprocessor, compiler, assembler, & linker)

gcc -o hello.exe hello.c

if you want to do each step manually:

  • preprocessing: via the GNU C Preprocessor (cpp.exe), which includes the headers (#include) and expands the macros (#define). The resultant intermediate file “hello.i” contains the expanded source code
    cpp hello.c > hello.i
    
  • compilation: The compiler compiles the pre-processed source code into assembly code for a specific processor. The -S option specifies to produce assembly code, instead of object code. The resultant assembly file is “hello.s
    gcc -S hello.i
    
  • assembly: The assembler (as.exe) converts the assembly code into machine code in the object file “hello.o
    as -o hello.o hello.s
    
  • linker: Finally, the linker (ld.exe) links the object code with the library code to produce an executable file “hello.exe
    ld -o hello.exe hello.o ...libraries...
    
  • execution:
    ./hello.exe
    
// Compile-only with -c option
> gcc -c hello.c
// Link object file(s) into an executable
> gcc hello.o