Ok, the most famous first program in any programming language is the ‘Hello World’ program, so I will explain how to create one in this post.
For my example, I will use ‘g++’ in a Linux environment, but ‘clang++’ works exactly the same way.
To write a ‘Hello World’ program in C++, you will need to create an empty file and name it with an appropriate extension (any name will do, for instance, HelloWorld.cpp). Common C++ file extensions include ‘.cpp’, ‘.cxx’, and ‘.cc’.
The compiler does not require the filename to match the name of any ‘class’ or other content inside the file. You can also store the file in any folder; there is no need to create it in a specific directory containing all the elements of a ‘package’ (like in Java).
Once you have created an empty HelloWorld.cpp file, you can open it in any text editor and start writing the following lines of code:
#include <iostream>
int main()
{
std::cout << "Hello world\n";
}
Save the file, open a terminal, navigate to the folder where your file is located, and then enter the following command:
g++ HelloWorld.cpp -o HelloWorld
If you do not receive any messages after entering the command, congratulations! Your program has compiled successfully. Otherwise, there is an error in your code that you will need to fix before compiling again.
Once it compiles correctly, you will need to run the program. In a Linux/Unix environment, you do this by typing ./ followed by the program’s name:
./HelloWorld
And the program output should be:
Hello world
Understanding how all of this works
The C++ compilation process consists of three main steps:
- Preprocessing: This step involves the preprocessor, which performs various text substitutions and transformations on your code before it is compiled.
- Compilation: During this phase, your code is converted into machine code, with placeholders for calls to functions that reside in external libraries.
- Linking: This step resolves those function calls by linking them to the actual functions in the libraries your program uses. If you do not specify any additional libraries (as in our example), your program will only be linked to the Standard Library, which comes with any C++ compiler.
#include
#include <iostream>
All lines starting with ‘#’ are called ‘preprocessor directives’. These are instructions that the preprocessor recognizes and executes.
#include tells the preprocessor to locate the file specified either inside quotes or between angle brackets and insert its content where the #include directive is used.
If the filename is enclosed in angle brackets (as in our case), the preprocessor searches for the file in a predefined directory that the compiler is aware of. For example, it will look for the file iostream in that directory. In a Linux environment, these files are typically located in a path similar to this one (I am using g++ 8.2):
/usr/include/c++/8
If the filename is declared between double quotes, it means the file will be in the current folder or in a folder explicitly specified when compiling the program.
iostream is the file that contains a lot of code allowing our programs to handle input and output. In our ‘Hello World’, we will need std::cout, which is defined in this file.
main function
int main()
When you invoke your program, the operating system needs to know which piece of code to execute. This code resides in the main function.
All functions must return something. For example, if you call a function sum that adds two numbers, it must return a value containing the result of the sum. So, the sum function must return an integer value (an int). Some old compilers allowed the main() function to return void (meaning ‘return nothing’), but the C++ standard specifies that main() must return an int value.
However, even if main() is declared to return an int, if you do not explicitly return anything, the compiler will not complain and will automatically return 0. Note that this behavior is exceptional and only allowed for the main() function.
The return value of the main() function indicates whether an error occurred. A return value of 0 means the program executed without errors, while a non-zero value indicates an error. The specific non-zero value depends entirely on the programmer’s design and error-handling mechanisms.
The program will continue running as long as the main() function is executing. Once its execution ends, the program terminates and returns the value to the operating system.
The body of any function is enclosed in curly braces.
std::cout
std::cout << "Hello world\n";
std::cout is a pre-existing object that represents command line output. The << operator essentially sends the text "Hello world\n" to the std::cout object, resulting in that text being displayed in the terminal.
The \n character sequence indicates a newline.
g++
g++ and clang are the most popular C++ compilers for Unix platforms today. You can replace one with the other almost without restrictions because clang was designed to be a drop-in replacement for g++.
When you say something like:
g++ HelloWorld.cpp
You are instructing the g++ compiler to go through the entire compilation process for the file HelloWorld.cpp. ‘Go through the entire compilation process’ in this case means running the preprocessor on the file, compiling it, linking it, and producing an executable.
Since I did not specify the name of the executable file in the command line example above, the g++ command generates a file called a.out in the current folder.
To specify the name of the file to be generated, you must invoke g++ with the -o option followed by the name of the executable file you want to create.