Configuring Visual Studio Code to compile C and C++ code

Some days ago a friend of mine asked me to recommend her an IDE to compile and run C and C++ code. And how I recently fell in love with Visual Studio Code, that was obviously my recommendation. But then I remembered that I had many years without coding on those languages and I had no idea if that was possible since VSC is not strictly an IDE but a Code Editor, and that’s how this post was born, looking for answers.

Disclaimer: I use macOS and this post is based on it.

First of all, we need to download and install Visual Studio Code of course.

The secret of VSC and why I love it, is that being a code editor you can customize it to work like an IDE by installing extensions.

Let’s proceed to install some extensions to be able to achieve our purpose: compile and run C and C++ code.

First, we are going to install the C/C++ extension from here, also we can open VSC, go to Code > Preferences > Extensions type C++ and press install. This extension will help us with the Intellisense like code completion, parameter info, quick info, etc.

placeholder

Now we need an extension to actually compile and run our code, the chosen one is Code Runner, we can download it from here, or follow the same process as the previous one.

Since I am using macOS and my friend too, the C/C++ compiler was already installed through Xcode tools. Code Runner just takes that compiler and run it in the terminal. If you don’t have it installed or are using another SO, make sure you have a compiler installed first.

After we install these two extensions we are ready to start. Let’s write our beloved Hello World.

#include <iostream>
using namespace std;
int main() 
{
    cout << "Hello world!";
    return 0;
}

Now let’s run it, there are three ways to do it:

  • Using Cmd+alt+n.
  • Using fn+F1 and type run code.
  • Right-click on the editor and select Run Code.

Any of these options will show the result in the OUTPUT tab in the bottom part of VSC.

placeholder

If we want to stop our program, we have two options:

  • Using Cmd+alt+m.
  • Using fn+F1 and type stop run code.

Until here everything seems fine, but soon we will discover that the OUTPUT tab is read-only, so, if our program needs input, we are doomed! Or not…

To fix this, we need to tell Code Runner to run our program in the TERMINAL instead of the OUTPUT tab using the next steps:

  • Go to Code > Preferences > Settings.
  • In the User tab on the left panel, expand the Extensions section.
  • Find and select Run Code Configuration.
  • Find and check the box Run in Terminal.

placeholder

Now your program will run in the TERMINAL tab and you will be able to type if you need to.

And that’s it, go and code in C/C++ using Visual Studio Code.