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
g++ --versionFor 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
How it all works?
Section titled “How it all works?”- You write your code in a file with extension
.cpp. For example:main.cpp - The you convert your CPP file to a machine executable using the compiler:
g++ main.cpp. - This creates an executable file which depends on the OS. For example, in Windows it creates
a.exewhereas in UNIX systems (Linux/Mac) it creates ana.out. - You can execute this file to run the program and get output.
./a.out - If you want to change the name of the executable, you can pass the
-oargument:g++ main.cpp -o main.out
Let’s try it out
Section titled “Let’s try it out”- Create a new file and open it in VSCode, or some text editor.
- Paste the following code
#include<iostream>
using namespace std;
int main() { cout<<"Hello World!"<<endl; return 0;}- Save the file with the name
main.cpp. - Now compile the file and create an executable using the following command:
g++ main.cpp -o main.out(Replace it withg++ main.cpp -o main.exein case of Windows machine) - You can see a new file
main.out(ormain.exe) got created in the same directory (or current working directory) - Let’s run the program now. Run
./main.outif you are in Unix systems (Mac / Linux) or.\main.exeif 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.