Compiling C++ in Terminal: A Step-by-Step Guide
Embarking on a journey into the world of C++ development often involves compiling your code from the terminal. This hands-on guide will walk you through the process, ensuring you're well-versed in compiling C++ in terminal environments like Linux, macOS, and Windows Subsystem for Linux (WSL).
Setting Up Your Environment
Before diving into the compilation process, ensure you have a suitable environment. For Linux and macOS, the GNU Compiler Collection (GCC) is typically pre-installed. If you're using WSL, install GCC using the following command:
sudo apt update
sudo apt install build-essential
For Windows, you can use MinGW or Cygwin, or set up WSL with a Linux distribution.

Writing Your First C++ Program
Let's start with a simple "Hello, World!" program to illustrate the compilation process:
// hello.cpp
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Compiling C++ Code
Now that you have your C++ code, it's time to compile it. Navigate to the directory containing your source file (hello.cpp) and use the following command:
g++ hello.cpp -o hello
g++: The GNU C++ compiler.hello.cpp: The source file you want to compile.-o hello: Specifies the output file name (hello).
If the compilation is successful, you'll see no output. If there are errors, the compiler will display them, and you'll need to address and fix them before proceeding.

Running the Compiled Program
After a successful compilation, you can run your program using the following command:
./hello
This will execute the compiled binary, and you should see the following output:
Hello, World!
Compiling with Debug Information
Including debug information in your compiled binary can be helpful for debugging. To do this, add the -g flag to your compilation command:
g++ -g hello.cpp -o hello
Compiling Multiple Source Files
As your projects grow, you'll likely have multiple source files. To compile them, use the following command, assuming you have two source files (hello.cpp and world.cpp):
g++ hello.cpp world.cpp -o my_program
This will compile both source files into a single binary (my_program).
Troubleshooting Common Issues
| Issue | Solution |
|---|---|
| Permission denied when running the compiled binary. | Use the chmod command to give execute permissions to the binary: chmod +x hello |
| Missing header files or libraries during compilation. | Install the required packages or ensure the correct include paths are set. |
And there you have it! You're now equipped to compile C++ code in the terminal like a pro. Happy coding!