Compiling C++ with g++
A simple guide to using g++, the default GNU compiler for C++ on macOS and Linux systems, to compile and run your code.
1. Basic Compilation
To compile a single C++ source file named main.cpp into an executable named a.out (the default):
g++ main.cpp
To run the compiled program:
./a.out
2. Naming Your Executable
You can use the -o flag to specify a custom name for your compiled binary. This prevents multiple compilation runs from overwriting the generic a.out.
g++ main.cpp -o my_program
./my_program
3. Enabling Warnings
It’s highly recommended to compile with warnings enabled. This helps catch potential bugs before they occur at runtime.
g++ -Wall -Wextra main.cpp -o my_program
-Wall: Enables almost all warnings about constructions that some users consider questionable.-Wextra: Enables some extra warning flags that are not enabled by-Wall.
4. Compiling Multiple Files
If your project spans multiple files (e.g., main.cpp, utils.cpp, math.cpp), you can compile them all together into a single executable:
g++ main.cpp utils.cpp math.cpp -o my_app
5. Using Modern C++ Standards
By default, g++ may not use the latest C++ standard. If you want to use features from C++11, C++14, C++17, or C++20, specify the -std flag:
# Compiling with C++17 standard
g++ -std=c++17 main.cpp -o my_app
# Compiling with C++20 standard
g++ -std=c++20 main.cpp -o my_app
If you get errors about missing modern C++ features, double-check your -std flag. The default standard for g++ changes depending on the compiler version installed!