g++: building C++ from the command line
Check the compiler
g++ is the C++ driver of the GCC toolchain: it runs the preprocessor, the compiler itself, the assembler and the linker, and it adds the C++ standard library on the link step. Ask it for its version first:
g++ --version
g++ (Alpine 15.2.0) 15.2.0 Copyright (C) 2025 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
A machine without a compiler answers command not found instead, and on Windows the message is 'g++' is not recognized as an internal or external command. On Ubuntu and Debian the package is g++, not gcc:
sudo apt install g++
Build and run one file
Save this program as hello.cpp. It prints two lines:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> langs{"C", "C++"};
for (const auto& lang : langs) {
std::cout << "Hello, " << lang << "!\n";
}
return 0;
}
One command builds it. -o names the executable, and the three warning flags make the compiler report what it usually keeps to itself:
g++ -std=c++23 -Wall -Wextra -Wpedantic hello.cpp -o hello
Run the file that appears in the current directory. The dot and the slash are part of the command: the shell does not look for programs in the current directory.
./hello
Hello, C! Hello, C++!
Without -o g++ writes a.out, the same default as gcc. That is why a forgotten -o ends with a fresh a.out next to the sources.
Choose the standard
-std= selects the language version. Without it the compiler picks its own default, which with GCC 15 is gnu++17, so a program that uses C++20 or C++23 features fails on a machine that builds it without this flag. Write the flag into the build script and the same code compiles everywhere.
| Flag | Standard | __cplusplus |
|---|---|---|
| -std=c++17 | C++17 | 201703L |
| -std=c++20 | C++20 | 202002L |
| -std=c++23 | C++23 | 202302L |
The macro proves which standard is active. Ask the preprocessor:
g++ -std=c++20 -dM -E -x c++ /dev/null | grep __cplusplus
#define __cplusplus 202002L
Warnings
A warning is not an error: the compiler still writes the executable. Read it anyway, because most warnings are real bugs. This program declares limit and never uses it:
#include <iostream>
int twice(int value)
{
int result = value * 2;
return result;
}
int main()
{
int limit = 10;
std::cout << twice(21) << '\n';
return 0;
}
g++ -std=c++23 -Wall -Wextra warn.cpp -o warn
warn.cpp: In function 'int main()': warn.cpp:11:9: warning: unused variable 'limit' [-Wunused-variable] 11 | int limit = 10; | ^~~~~
The message names the file, the line and the column, the rule and the flag that owns the rule. To chase one warning instead of all of them, pass its flag alone, for example -Wunused-variable. To silence a known warning: -Wno-unused-variable.
Errors
An error stops the build and no executable is written. A missing semicolon is the classic case:
#include <iostream>
int main()
{
std::cout << "one" << '\n'
return 0;
}
g++ -std=c++23 -Wall broken.cpp -o broken
broken.cpp: In function 'int main()': broken.cpp:5:31: error: expected ';' before 'return' 5 | std::cout << "one" << '\n' | ^ | ; 6 | return 0; | ~~~~~~
The compiler points at the line after the real mistake and even draws
the missing character. Fix the first error first: one missing semicolon
often produces a page of follow-up messages.
A message from the linker instead of the compiler looks different:
undefined reference to .... It means the
declaration was found and the definition was not, so the object file or
the library that holds it is missing from the command line.
Object files and the link step
-c compiles and stops before the link, one object file per source file. A project of three files shows the two steps. First the declaration, in functions.h:
#pragma once
double add(double a, double b);
Then the definition in functions.cpp and the caller in main.cpp:
#include "functions.h"
double add(double a, double b)
{
return a + b;
}
#include <iostream>
#include "functions.h"
int main()
{
std::cout << add(2, 3) << '\n';
std::cout << add(1.5, 2.5) << '\n';
return 0;
}
g++ -std=c++23 -Wall -Wextra -c functions.cpp -o functions.o
ls -l functions.o
-rw-r--r-- 1 user user 1240 Nov 17 19:33 functions.o
The object file holds machine code and the names it needs from other files. The link step takes the object files plus the C++ standard library and writes the executable:
g++ -std=c++23 -Wall -Wextra main.cpp functions.o -o app
./app
5 4
The same line with both sources, g++ main.cpp functions.cpp -o app, does the compile and the link in one go. The two-step form is faster while only one file changes: functions.o stays as it is.
A shared library
-fPIC -shared builds a shared library from the same kind of source. The header point.h declares distance, point.cpp defines it and use.cpp calls it:
#include "point.h"
double distance(double x)
{
return x < 0 ? -x : x;
}
g++ -std=c++23 -fPIC -shared point.cpp -o libpoint.so
-L. adds the current directory to the search path and -lpoint asks for libpoint.so: the prefix and the suffix are part of the file name, not of the flag.
g++ -std=c++23 use.cpp -L. -lpoint -o use
LD_LIBRARY_PATH=. ./use
3.5
Without LD_LIBRARY_PATH the program starts and fails with error while loading shared libraries: libpoint.so: cannot open shared object file: the linker recorded the name of the library and the loader has no directory to look in.
Optimization and debug info
Two flags cover most builds. -g writes debug info for gdb and the sanitizers, and -O2 asks the optimizer for speed:
g++ -std=c++23 -O2 hello.cpp -o hello_o2
ls -l hello hello_o2
-rwxr-xr-x 1 user user 41344 Nov 17 19:33 hello -rwxr-xr-x 1 user user 19520 Nov 17 19:33 hello_o2
The optimized file is smaller here because the optimizer removed the
loop over a vector of two strings and printed both lines directly. The
sizes move with the code, the compiler and the platform; compare them on
your own program with
hyperfine rather than reading too much into this
pair.
-O0 is the default and the level that matches
the source line by line. -O3 adds vectorization.
A release build usually passes -O2 -DNDEBUG.
Sanitizers
The address sanitizer catches memory errors at run time. The program below allocates an array and never releases it:
#include <iostream>
int main()
{
int* data = new int[4]{1, 2, 3, 4};
std::cout << data[0] << '\n';
return 0;
}
g++ -std=c++23 -g -fsanitize=address leak.cpp -o leak
./leak
1 ================================================================= ==355==ERROR: LeakSanitizer: detected memory leaks Direct leak of 16 byte(s) in 1 object(s) allocated from: #0 0x7f8c4ed4374d in operator new[](unsigned long) (/usr/lib/libasan.so.8+0xee74d) #1 0x57c7447ff206 in main leak.cpp:5 #2 0x7f8c4f35a153 in libc_start_main_stage2 src/env/__libc_start_main.c:95 SUMMARY: AddressSanitizer: 16 byte(s) leaked in 1 allocation(s).
The addresses, the process number and the long build id after the library path change with every machine and every build; the allocation in leak.cpp line 5 does not. -fsanitize=undefined catches signed overflow, shifts by a wrong amount and similar undefined behaviour, -fsanitize=thread catches data races. Sanitizer builds are two to three times slower, so they never go to production.
g++ in make
make reads the compiler from the CXX variable, which already points at g++, and the flags from CXXFLAGS. A Makefile for the three-file project:
CXX ?= g++
CXXFLAGS ?= -std=c++23 -Wall -Wextra -O2
app: main.o functions.o
$(CXX) $(CXXFLAGS) $^ -o $@
%.o: %.cpp functions.h
$(CXX) $(CXXFLAGS) -c $< -o $@
clean:
rm -f *.o app
make
The make lesson of the course takes this file apart; the CMake lesson does the same for CMake, where the compiler is detected and the flags go into CMAKE_CXX_FLAGS.
The flags used here
| Flag | What it does |
|---|---|
| -std=c++23 | Language version: 17, 20, 23 |
| -o name | Name of the output file |
| -c | Compile to an object file, do not link |
| -Wall | The warnings everybody wants |
| -Wextra | More warnings on top of -Wall |
| -Wpedantic | Warn about anything outside the standard |
| -Werror | Turn every warning into an error |
| -g | Debug info for gdb and sanitizers |
| -O2 | Optimize, the usual release level |
| -I dir | Add a directory for #include |
| -L dir | Add a directory for libraries |
| -l name | Link a library, libname.so |
| -fPIC -shared | Build a shared library |
| -fsanitize=address | Memory checks at run time |
Every command on this page was run with g++ 15.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev