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.cppis your C++ source code file.-otells the compiler to name the output executable.output_executableis 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
-ooption, which results in an executable nameda.outby 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
| Command | Description |
|---|---|
| g++ file.cpp | Compile file.cpp to default executable a.out |
| g++ file.cpp -o program | Compile file.cpp to executable named program |
| ./program | Run the compiled executable named program |
| g++ -Wall file.cpp -o program | Compile with all warnings enabled |
| g++ -std=c++17 file.cpp -o program | Compile 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.