How to Compile C++ Code

by iamvkr on

Running Your First C++ Program

This guide will walk you through the process of setting up your environment and running a simple C++ program.

1. Installation

  • Install a C++ Compiler:
    • Windows: Download and install MinGW (Minimalist GNU for Windows). This package includes the GCC (GNU Compiler Collection) compiler.
    • macOS: C++ is generally pre-installed on macOS. You can use the clang compiler from the command line.
    • Linux: C++ is typically installed by default. You can use the g++ compiler from the terminal.

2. Set Environment Variables (Optional)

  • Windows:
    • Right-click “This PC” and select “Properties.”
    • Click on “Advanced system settings.”
    • Go to the “Environment Variables” tab.
    • In the “System variables” section, find the “Path” variable and click “Edit.”
    • Add the path to your compiler’s bin directory (e.g., C:\MinGW\bin) to the list.
    • Click “OK” to save the changes.

3. Create a C++ File in VS Code

  • Open VS Code.
  • Create a new file (File > New File) and save it with a .cpp extension (e.g., hello.cpp).

4. Write Your C++ Code

#include <iostream>

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

5. Compile and Run

Open the integrated terminal in VS Code (Terminal > New Terminal).

Navigate to the directory where you saved your hello.cpp file using the cd command.

Compile the code using the following command:

g++ hello.cpp -o hello

This command will create an executable file named hello.

5. Run the Program

./hello

You should see the output:

Hello, world!

Congratulations! You have successfully compiled and run your first C++ program.