0
0
CppHow-ToBeginner · 3 min read

How to Compile C++ Program from Command Line Quickly

To compile a C++ program from the command line, use the g++ compiler followed by your source file name and the -o option to specify the output executable. For example, g++ program.cpp -o program compiles program.cpp into an executable named program.
📐

Syntax

The basic command to compile a C++ program is:

  • g++ source_file.cpp -o output_executable

Here:

  • g++ is the C++ compiler command.
  • source_file.cpp is your C++ source code file.
  • -o tells the compiler to name the output executable.
  • output_executable is the name you want for the compiled program.
bash
g++ source_file.cpp -o output_executable
💻

Example

This example shows how to compile and run a simple C++ program that prints "Hello, world!".

cpp
#include <iostream>

int main() {
    std::cout << "Hello, world!" << std::endl;
    return 0;
}
Output
Hello, world!
⚠️

Common Pitfalls

Common mistakes when compiling C++ programs include:

  • Forgetting to specify the -o option, which results in an executable named a.out by default.
  • Using the wrong file extension or misspelling the source file name.
  • Not having g++ installed or not added to your system's PATH.
  • Trying to run the source file instead of the compiled executable.
bash
/* Wrong: missing -o option, executable will be named a.out */
g++ program.cpp

/* Right: specify output executable name */
g++ program.cpp -o program
📊

Quick Reference

CommandDescription
g++ file.cppCompile file.cpp to default executable a.out
g++ file.cpp -o programCompile file.cpp to executable named program
./programRun the compiled executable named program
g++ -Wall file.cpp -o programCompile with all warnings enabled
g++ -std=c++17 file.cpp -o programCompile using C++17 standard

Key Takeaways

Use g++ source.cpp -o output to compile C++ programs from the command line.
The -o option sets the name of the output executable file.
If -o is omitted, the executable defaults to a.out.
Make sure g++ is installed and accessible in your system PATH.
Run your program by typing ./output on Unix or output.exe on Windows.