All articles
c

Run C/C++ programs with VS Code

Share this article

Share on LinkedIn Share on X (formerly Twitter)

Introduction

You may have tried running C/C++ programs using VSCode before. If you are not successful in doing so, this tutorial is for you. In this article I will show you how you can setup your machine and VSCode to be able to run C/C++ programs.

Setup

First, you need to configure VSCode GCC C++ compiler (g++) and GDB debugger from Mingw-w64 to create programs that run on Windows.

  • [x] Go to MinGW - Getting Started
  • [x] Under 'Graphical User Interface Installer', download the automated GUI installer assistant called mingw-get-setup.exe
  • [x] Continue installation with default options, mark the following from MinGW Installation Manager
    1. mingw32-base-bin
    2. mingw32-gcc-g++-bin
  • [x] Go to Installation → Apply Changes → Apply
  • [x] After the installation is complete, close all the popup windows.
  • [x] Add gcc to PATH Environment variable, generally it will be C:\MinGW\bin
  • [x] Install the C/C++ extension for VS Code.

Your first C program

#include <stdio.h>
 
int main(int argc, char **argv)
{
  printf("Hello World!");
  return 0;
}

Configuration

Create a file .vscode\c_cpp_properties.json for configuring VSCode(using the extension - C/C++ extension)

{
  "configurations": [
    {
      "name": "Win32",
      "includePath": ["${workspaceFolder}/**"],
      "defines": ["_DEBUG", "UNICODE", "_UNICODE"],
      "windowsSdkVersion": "8.1",
      "compilerPath": "C:/MinGW/bin/gcc",
      "cStandard": "c11",
      "cppStandard": "c++17",
      "intelliSenseMode": "${default}"
    }
  ],
  "version": 4
}

Compiling your C programs

  • [x] Run gcc ./main.c -o ./main

This command will compile the c program and creates an executable .exe.

  • [x] Now run main.exe or ./main.exe

This command will print Hello World! in the terminal.

Script

I have created a bash script to run c programs. Using this script you can run your c programs in one go like ./c.sh main.c

The script will create a .exe file, executes it and deletes it.

#!/bin/bash
 
gcc `pwd`/$1 -o `pwd`/${1%%.*} && `pwd`/${1%%.*}.exe && rm `pwd`/${1%%.*}.exe

Other robust script that I use is:

#!/bin/bash
 
# Get the filename w/ extension
FILE="$(basename -- $1)"
 
# Get the filename without extension
fn=${FILE%%.*}
 
# Get the directory
SRC="$(dirname $1)"
 
echo -e "\033[0;34mCompiling $FILE \033[0m"
gcc $1 -o $SRC/$fn
 
echo -e "\033[0;34mRunning $FILE \033[0m"
$SRC/$fn.exe
 
rm $SRC/$fn.exe
echo -e "\n\033[0;32mDeleted $SRC/$fn.exe successfuly!\033[0m";
 
# Example - How to use
# ./runc.sh ./world.c
# ./runc.sh ./programs/hello.c
# ./runc.sh ../c-programs/programs/hello.c

Resources

Official VSCode Artile - Using GCC with MinGW


Comments