Install C++ and Run Hello World
Set up a compiler, write your first source file, and run the classic Hello World program.
— Laozi
Setting up a fully functional C++ environment can take some time, and it would make a Hello World article more complicated than necessary. Our goal here is to try C++ with as little effort as possible. So, for now, we are going to take the most direct path to our first result, even if that means cutting a few corners.
To run our first code, we need to make sure that a C++ compiler is installed. While the choice of compiler is entirely up to the user, I am going to provide quick installation guides for different operating systems to help get the Clang++ compiler installed with minimal effort:
winget install -i -e --id LLVM.LLVM
# Make sure the compiler’s binary folder,
# usually C:\Program Files\LLVM\bin, is added
# to the PATH environment variable.
# Then reopen the terminal and test it:
clang --versionsudo apt update
sudo apt install -y clang lld lldb
clang --versionsudo yum module install -y llvm-toolset
sudo yum install -y lldb python3-lit
clang --versionCreate a file named hello.cpp and add the following code.
#include <iostream>
int main() {
std::cout << "Hello ;)";
}
#include <iostream> is a preprocessor directive. It lets our program use the standard C++ input and output tools, such as std::cout, which we use to print text to the screen.
int main() is the beginning of the main function definition. A C++ program can have many functions, but main is special because it is the starting point of the program and it can be defined only once. When the program starts, execution begins in the main function, and the statements inside it are run one by one.
Curly brackets { and } show which lines of code belong to the function. Everything inside them is part of that function.
std::cout is the standard output stream in C++. We use it to send text or other values from our program to the screen, usually to the console window. The double angle brackets << are called the stream insertion operator. They send the value on the right into std::cout, so it can be displayed.
Compilation turns your human-readable source file into a binary that the computer can execute directly. We will do this in two simple steps:
clang++ hello.cpp -o hello.exe
hello.execlang++ hello.cpp -o hello
./helloclang++ hello.cpp -o hello
./helloThe first command compiles hello.cpp and writes the result to a file named hello. The second command runs it. You should see Hello ;) printed in the terminal.