0
0
CppHow-ToBeginner · 3 min read

How to Run a C++ Program in Terminal: Step-by-Step Guide

To run a C++ program in the terminal, first compile the source code using g++ filename.cpp -o outputname. Then execute it by typing ./outputname in the terminal.
📐

Syntax

Use the g++ command to compile your C++ source file. The general syntax is:

  • g++ filename.cpp -o outputname: Compiles filename.cpp into an executable named outputname.
  • ./outputname: Runs the compiled program in the terminal.
bash
g++ filename.cpp -o outputname
./outputname
💻

Example

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

cpp
#include <iostream>

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

Common Pitfalls

Common mistakes when running C++ programs in the terminal include:

  • Forgetting to compile before running the program.
  • Not using ./ before the executable name on Unix-like systems.
  • Typos in file names or executable names.
  • Not having g++ installed or not added to your system's PATH.
bash
# Wrong: Trying to run source file directly
./filename.cpp

# Right: Compile then run
g++ filename.cpp -o filename
./filename
📊

Quick Reference

Remember these quick steps to run your C++ program:

  • Compile: g++ yourfile.cpp -o yourprogram
  • Run: ./yourprogram
  • Check for errors during compilation and fix them before running.

Key Takeaways

Always compile your C++ source code with g++ before running it.
Use ./ before the executable name to run it in the terminal on Unix-like systems.
Check for compilation errors and fix them before trying to run the program.
Make sure g++ is installed and accessible in your system's PATH.
Use clear and consistent file and executable names to avoid confusion.