Learning C++: Preprocessor, Compiler, Linker and “Hello, World!”

An example "Hello World" in C++

My blog posts on C++ so far have looked at the basic data types and arrays, structs, enums and unions. With this blog post I am going to look at the 3 steps used to compile C++ and a brief look at writing “Hello, World!” in C++.

C++ is a compiled language, which means that the code is compiled before it can be run, unlike Python or JavaScript which are interpreted languages. Although C++ code needs to be compiled before it is run, the compiling is actually three different stages with only one being called compiler. These three stages are:

  • Preprocessor
  • Compiler
  • Linker

I am going to take a very brief look at each stage.

Preprocessor

Reads information such as #include <> and then includes information about the libraries being included into the program. The output from the preprocessor is stored in a translation unit.

Compiler

Reads the a translation unit and outputs an object file which contains machine code. Different platforms have different compilers. The compiler checks for syntax errors.

Linker

The linker takes the object file and outputs an executable. Along the way the linker also makes sure the outputted program knows how to use the linked in libraries (i.e. it puts the code for those library functions into the executable).

Hello, World!

As is customary for most new programmers being introduced to a programming language it is time for a “Hello, World!”

An example "Hello World" in C++
An example “Hello World” in C++

There are at least two ways to write Hello World in C++

#include <cstdio>

int main() {
   printf("Hello, World!");
   return 0;
}

or

#include <iostream>

int main() {
   std::cout<<"Hello, World! \n";
   return 0
}

The first line of the both my Hello World examples starts with #include , which is like the import option in Python. In one example I am using the cstdio library (C STandarD Input Output) and the iostream library in other.

The printf command is print format and I use it to output the line hello world, then ask the program to return 0 (indicating success). More information on cstdio can be found at:
http://www.cplusplus.com/reference/cstdio/

The cout command does a similar job, outputting to the standard output stream (std), and again returning a 0 to indicate success. More information on cout can be found at: http://www.cplusplus.com/reference/iostream/cout/

int main() is the entry point into the program, C++ programs have a single entry point.