Here’s a quick breakdown of every piece in
g++ -std=c++17 -o your_program_name your_program_name.cpp -Wall -O2
| Piece | Meaning | Why you’d use it |
|---|
g++ | The GNU C++ compiler (front-end to GCC). | Compiles and links C++ source code into an executable. |
-std=c++17 | Tells the compiler to follow the C++17 language standard. | Grants you access to all C++17 features (e.g., std::optional, structured bindings, if constexpr, parallel algorithms). |
-o your_program_name | Sets the output file’s name. | Instead of the default a.out (Linux/macOS) or a.exe (Windows), the resulting executable will be called your_program_name. |
your_program_name.cpp | The source file you want to compile. | Can be one or many files; you can list them all here or use wildcards/globbing. |
-Wall | “Warn-all” → enables a broad set of compiler warnings. | Helps catch common mistakes (unused variables, signed/unsigned mismatches, etc.). |
-O2 | Optimization level 2. | Generates faster code without (usually) increasing compile time or risk as much as higher levels like -O3. |
Putting it together, the command:
- Invokes
g++.
- Compiles
your_program_name.cpp using the C++17 rules.
- Turns on most of GCC’s useful warnings.
- Optimizes the generated machine code at level 2.
- Produces an executable named
your_program_name.
Notes & tips
• You can swap the order of the options (except the -o <name> needs its argument right after it).
• If you have multiple .cpp files:
g++ -std=c++17 -Wall -O2 file1.cpp file2.cpp -o app
• For even stricter warnings, many developers add -Wextra -Wpedantic -Werror.
• Debug build? Replace -O2 with -O0 -g to disable optimizations and include debug symbols.
• CMake or Makefiles are handy so you don’t type this every time.