Compiling and running C++ from the command line is a two step ritual that you will perform hundreds of times. You translate the source file into an executable with the compiler, and then you execute that executable. Once the exact command is muscle memory you stop thinking about the toolchain and you start thinking about your program.
The previous lesson in this module covered "What Does Your First C++ Program Look Like?", and the next lesson in this module is about "What Are the Parts of a C++ Program: main, Statements and Blocks?".
The two commands that matter
Everything about compiling and running C++ from the command line fits into one line for a single file program.
g++ -std=c++17 -Wall -Wextra main.cpp -o program
./programThe first command compiles, and the second one runs. On Windows the second command becomes program.exe, and in the Windows Command Prompt it is just program.
Here is the compile command broken down piece by piece.
g++is the driver that runs the preprocessor, the compiler, the assembler and the linker for you. Using the g++ driver rather than the raw gcc is what makes the C++ standard library headers work correctly.-std=c++17is the language standard. C++17 is the safe default for everything in this tutorial.-Wall -Wextraturn on warnings. These are advice from the compiler about code that is legal but is probably wrong.- main.cpp is the source file.
-o programis the name of the executable that comes out. Without it the binary is called a.out on Linux and macOS.
The order of those flags does not matter to the compiler, but keeping them in this order makes your commands easy to read at a glance.
Watching the compiler work
Add -v and the compiler narrates every step that it takes, and that is the fastest way to understand what compiling actually involves.
g++ -std=c++17 -Wall -Wextra -v main.cpp -o program 2>&1 | head -40You will see the search paths for headers, the invocation of the preprocessor, the compiler proper, the assembler, and finally the linker. Notice how many separate programs are involved. The linker is the last step, and it is the one that reports the most common beginner error. That error is an undefined reference, and it means that a function was called but its definition was never handed to the linker.
The program the commands refer to
Every command in this lesson compiles the same small program, so that the flags can be compared against a known result.
#include <iostream>
int main() {
double celsius = 21.5;
std::cout << "fahrenheit: " << celsius * 9.0 / 5.0 + 32.0 << '\n';
return 0;
}Building it with the flags from this lesson produces a binary that prints 70.7. Adding -Wall changes nothing about the output, but it tells you about the problems that the compiler is able to see on its own.
One program, two files
Real projects are split across files, and the command line for that is a list of source files rather than one. The header below holds the shared interface, and the implementation and the entry point live in a second file.
#include <string>
// greeting.hpp — the interface shared by the two files
std::string greeting_for(const std::string& name);The second file includes the header, defines the function and provides main.
#include <iostream>
#include <string>
// greeting.cpp — the implementation
std::string greeting_for(const std::string& name) {
return "Hello, " + name + "!";
}
// main.cpp — the entry point
int main() {
std::cout << greeting_for("world") << '\n';
return 0;
}The output is the familiar greeting.
Hello, world!Building the two files together is a single command that names both source files.
g++ -std=c++17 -Wall -Wextra greeting.cpp main.cpp -o greeting
./greetingCommon compiler errors you will meet today
Three messages account for most first day failures.
error: 'cout' was not declared in this scope
error: expected ';' before '}' token
undefined reference to 'foo'The first one usually means a missing #include <iostream> or a missing std:: prefix. The second one is almost always a missing semicolon. The third one means that a function is declared or called but never defined in any file that was compiled and linked together.
Reading a compiler error takes practice, and the trick is to read it from the bottom up. The first error is usually the real one, and everything after it is often a cascade that was caused by the parser losing its place.
Rebuilding after every edit
Compilation takes time, and you will make many small edits. The classic loop is edit, compile, run. The mistake is running the previous binary and wondering why your change did nothing.
Two habits prevent that entirely. The first one is to put the compile and run steps in one command, so that the build can never be skipped.
g++ -std=c++17 -Wall -Wextra main.cpp -o program && ./programThe && means that the program only runs if the compile succeeded. The second habit is to turn on the dependency checker and let the build tool rebuild only what changed.
g++ -std=c++17 -Wall -Wextra -MMD -MP main.cpp -o programThat adds a dependency file next to the object file, and that is what build tools such as make and CMake use to decide what needs recompiling. You do not need to know the details yet. The point is that a manual one file workflow and an automatic build workflow agree on what changed.
Where the output file goes
The -o flag controls the output path and the directory. If you omit it, then the binary lands in the current directory under a default name, and that name is a.out on Linux and macOS.
# put the binary somewhere specific
g++ -std=c++17 main.cpp -o build/program
# create the folder first, or the compiler will complain
mkdir -p build && g++ -std=c++17 main.cpp -o build/programOn Windows the compiler appends .exe automatically, so -o program produces program.exe. Passing -o program.exe explicitly also works, and it makes shell scripts portable between the two worlds.
Sanitizers turn on the bug detectors
The single highest value flag for a beginner is the address sanitizer. It instruments the compiled code, so that a mistake which would otherwise corrupt memory or read out of bounds is caught immediately, with a message that names the line.
g++ -std=c++17 -Wall -Wextra -g -fsanitize=address,undefined main.cpp -o program
./programAdd -g so that the debugger can map the report back to source lines. The undefined behaviour sanitizer catches a second family of problems. It finds signed integer overflow, misaligned access, and other operations that the C++ standard says are undefined rather than merely wrong. Together these two tools catch most of the bugs that would otherwise appear as random crashes hours later.
Quick reference
- Compile with
g++ -std=c++17 -Wall -Wextrafile.cpp -o name, and then run./name. -onames the output, and omitting it gives a.out.- Read compiler errors from the bottom up, and fix only the first one.
- Chain compile and run with
&&so that you never run a stale binary. - Add
-g -fsanitize=address,undefinedwhile you are learning, because it finds bugs at the exact line. - On Windows the binary is name.exe, and it runs as name or
.\name.
Try it yourself: compile the hello world program, and then introduce three deliberate mistakes one at a time. Try a missing semicolon, then a missing #include, and then a call to a function that you never defined. For each one, record the exact error text and the line that the compiler pointed at. Then rebuild with the sanitizers enabled and confirm a clean run.