Tutorials / C++: From Basics to Modern C++ / Setting up a C++ compiler and writing your first program

Setting up a C++ compiler and writing your first program

14 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. Final project: a command-line expense tracker

What you need to start

C++ is a compiled language. You write source text, a program called the compiler turns it into machine code, and then you run the result. There is no interpreter waiting to read your file line by line. That is why C++ programs are fast, and also why the first hour feels fussier than Python or JavaScript.

Three compilers matter in practice. They all implement the same language, and the code in this course works on any of them.

CompilerWhere you usually find itInstall
g++ (GCC)Linux, and Windows through MSYS2 or MinGWOn Debian or Ubuntu: sudo apt install g++
clang++macOS, and many Linux setupsOn macOS: xcode-select --install
MSVC (cl)Windows, with Visual Studio or Build ToolsInstall the "Desktop development with C++" workload

I use all three, depending on the machine. If you are on Windows and want the least friction, install Visual Studio Build Tools and open the "Developer Command Prompt", because that prompt has cl on its path already. Check what you have by asking for a version:

g++ --version
clang++ --version
cl

Running cl alone prints a banner with a version number. Any recent release of these compilers supports C++17 fully and most of C++20, which is what we need.

Your first program

Create a folder, and inside it a file called hello.cpp. Type this in. Do not copy it blindly the first time; typing it helps you notice the details.

#include <iostream>

int main() {
    std::cout << "Hello from C++\n";
    return 0;
}

Walking through it

  • #include <iostream> pastes in the declarations for input and output streams. Without it, the compiler has never heard of std::cout.
  • int main() is where every program starts. It returns an int, which is the exit code the operating system sees. Zero means success.
  • std::cout is the standard output stream. The << operator sends things into it. Here we send a string.
  • "\n" is a newline character. You will also see std::endl, which adds a newline and flushes the buffer. Flushing is slow if you do it a lot, so I prefer "\n".
  • Every statement ends with a semicolon. The braces { } mark a block.

The std:: prefix means "from the standard library". C++ keeps library names inside the namespace std so they do not collide with your own names. You will see tutorials that write using namespace std; at the top. It saves typing, but it pulls every standard name into your scope, and in a big project that causes confusing clashes. Get used to writing std:: from day one.

Compile and run

Open a terminal in the folder. With g++ or clang:

g++ -std=c++20 -Wall -Wextra hello.cpp -o hello
./hello

On Windows with MSVC, from the Developer Command Prompt:

cl /std:c++20 /EHsc /W4 hello.cpp
hello.exe

Let me explain the flags, because beginners tend to skip them. -std=c++20 picks the language version; without it you get whatever default your compiler ships. -Wall -Wextra turn on warnings. /W4 does the same on MSVC. /EHsc enables normal exception handling on MSVC. Warnings catch real bugs, such as unused variables and comparisons between signed and unsigned numbers, so turn them on now and keep them on.

What happens behind that one command? The preprocessor handles #include lines. The compiler turns your code into an object file. The linker joins that object file with the standard library and produces the executable. When you see error messages, it helps to know which stage failed. A message with a line number is a compiler error. A message about "undefined reference" or "unresolved external" comes from the linker.

Reading your first errors

Delete the semicolon after the std::cout line and compile again. You get an error that points to the line after the real problem, because the compiler only noticed something was wrong when it reached the next token. This is normal. When an error looks strange, look at the line above it. Also, always fix the first error in the list first. Later errors are often just fallout from the first one.

Comments

Use // for a comment to the end of the line, and /* ... */ for a block. Comments should explain why, not repeat what the code says.

// Print a greeting, then exit with code 0.
int main() {
    /* the block form works across several lines,
       but I rarely use it */
    return 0;
}

The common mistake

The most common beginner problem is not a syntax slip. It is editing the file, forgetting to save, and running the old executable. The second most common is saving the file as hello.cpp.txt because the editor or Windows hid the extension. Turn on "show file extensions" in Windows Explorer and check the name. Third, people compile with gcc instead of g++ on a .cpp file and get linker errors about missing library functions. Use g++ for C++.

Try it yourself

  1. Compile and run the hello program using the compiler you installed.
  2. Change the message and print two lines using two std::cout statements.
  3. Remove #include <iostream> and read the error message. Put it back.
  4. Compile once without -Wall -Wextra and once with them. Add the line int unused = 5; inside main and see which build warns you.
cpp
g++ --version
clang++ --version
cl

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account