C++ Tutorial
Class and Object
Reference
Inheritance and Derivation
Polymorphism and Virtual Functions
Operator Overloading
Template
Exception
Object Oriented Advanced
Input/Output Stream
File Operations
To compile and run a C++ program, you need to follow these steps:
Write the C++ code and save it in a file with a .cpp
extension, for example, my_program.cpp
.
Install a C++ compiler if you haven't already. A widely used compiler is the GNU Compiler Collection (GCC). For Windows, you can download the MinGW-w64 compiler from https://mingw-w64.org. On Linux, you can usually install GCC using the package manager (e.g., sudo apt install g++
on Ubuntu). On macOS, you can install GCC using Homebrew (brew install gcc
) or MacPorts (sudo port install gcc
).
Open a terminal (Command Prompt on Windows, Terminal on macOS or Linux) and navigate to the directory where the C++ source file is saved using the cd
command.
Compile the C++ code using a compiler. If you're using GCC, the command is:
g++ -o my_program my_program.cpp
This command compiles my_program.cpp
and creates an executable named my_program
(or my_program.exe
on Windows). The -o
flag is used to specify the output file name. If the compilation is successful and there are no errors in your code, you'll see no output from the compiler. If there are errors, the compiler will display them, and you'll need to fix them before trying to compile again.
Run the compiled program. The command depends on your operating system:
.\my_program
./my_program
This command will execute the compiled program, and you should see the output of your program in the terminal.
In summary, to compile and run a C++ program:
.cpp
file..cpp
file.g++ -o my_program my_program.cpp
../my_program
(macOS and Linux) or .\my_program
(Windows).Using a C++ compiler for beginners:
#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; }
#include <iostream> int main() { std::cout << "Hello, World!" << std::endl return 0; }