Skip to content

C++ Setup (1)

Course: C++ Part 1 - chapter 1

Installing compiler and configuring with VS Code

Section titled “Installing compiler and configuring with VS Code”

For compiling C++ programs to machine code (executables), you need g++ compilers. Generally with Mac and Linux, g++ comes preinstalled. Check using the command

Terminal window
g++ --version

For installing on Windows, you need to install mingw and then add it to PATH. Tutorial: https://code.visualstudio.com/docs/cpp/config-mingw#_prerequisites

You can also setup a VS Code extension for features like Code Completion, Running on VS Code by clicking button etc.

https://code.visualstudio.com/docs/languages/cpp

https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner

  1. You write your code in a file with extension .cpp. For example: main.cpp
  2. The you convert your CPP file to a machine executable using the compiler: g++ main.cpp.
  3. This creates an executable file which depends on the OS. For example, in Windows it creates a.exe whereas in UNIX systems (Linux/Mac) it creates an a.out .
  4. You can execute this file to run the program and get output. ./a.out
  5. If you want to change the name of the executable, you can pass the -o argument: g++ main.cpp -o main.out
  1. Create a new file and open it in VSCode, or some text editor.
  2. Paste the following code
Terminal window
#include<iostream>
using namespace std;
int main() {
cout<<"Hello World!"<<endl;
return 0;
}
  1. Save the file with the name main.cpp.
  2. Now compile the file and create an executable using the following command: g++ main.cpp -o main.out (Replace it with g++ main.cpp -o main.exe in case of Windows machine)
  3. You can see a new file main.out(or main.exe) got created in the same directory (or current working directory)
  4. Let’s run the program now. Run ./main.out if you are in Unix systems (Mac / Linux) or .\main.exe if you are in Windows machine. You should see “Hello World!” printed on your terminal.

💡 In most cases you would not need a local setup, there are many online IDEs out there and most platforms also gives you with an IDE. However, it is always good to learn to set it up locally and how to compile and run a C++ code. In some platforms (like Codeforces) you don’t get an IDE and also when you attend onsite programming contests, it might be faster for you to write things locally than on an online IDE.