Home

Run C/C++ programs with VS Code

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.

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

This command will compile the c program and creates an executable .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



Last Updated on

Next Post: Rules vs Guidelines →

Comments