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

How To Compile And Run A C++ Program?

To compile and run a C++ program, you need to follow these steps:

  1. Write the C++ code and save it in a file with a .cpp extension, for example, my_program.cpp.

  2. 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).

  3. 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.

  4. 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.

  1. Run the compiled program. The command depends on your operating system:

    • Windows: .\my_program
    • macOS and Linux: ./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:

  1. Write and save the C++ code in a .cpp file.
  2. Install a C++ compiler, such as GCC.
  3. Open a terminal and navigate to the directory containing the .cpp file.
  4. Compile the C++ code using a command like g++ -o my_program my_program.cpp.
  5. Run the compiled program using a command like ./my_program (macOS and Linux) or .\my_program (Windows).
  1. Using a C++ compiler for beginners:

    • Description: Introduces the concept of a C++ compiler and how to use it to convert C++ source code into executable programs.
    • Example Code: A simple "Hello, World!" program to demonstrate basic compilation.
    #include <iostream>
    
    int main() {
        std::cout << "Hello, World!" << std::endl;
        return 0;
    }
    
#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl
    return 0;
}