Primo Software

Getting Started with C++ and Visual Studio Code on Ubuntu

Before going through these steps make sure you have done Setup C++ development environment on Ubuntu

Visual Studio Code

Download and install from Visual Studio Code site.

Open Visual Studio Code and press Cmd + Shift + P. Select Shell Command: Install 'code' command in PATH.

C++ Project

Create a directory called simple in ~/cpp/simple

mkdir -p ~/cpp/simple

Open the directory in Visual Studio Code:

cd ~/cpp/simple
code .

Install the C/C++ Extension Pack.

Project Files

Add the following files:

src/main.cpp

#include <iostream>

int main() {
  std::cout << "Hello CMake!\n";
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)

project(simple)

add_executable(simple src/main.cpp)

build.sh

#!/usr/bin/env bash

mkdir -p ./build/debug
pushd ./build/debug
    cmake -G 'Ninja' -DCMAKE_BUILD_TYPE=Debug  ../.. && \
    ninja
    ret=$?
popd  

Make it executable:

chmod +x build.sh

.gitignore

.cache/
build/

Test the build

Open Terminal in Visual Studio Code and test the build from command line:

./build.sh

Automate the build

Add the following Visual Studio Code specific files to the .vscode subdir:

.vscode/tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Build",
            "type": "shell",
            "linux": {
                "command": "${workspaceFolder}/build.sh",
            },
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Test the build by pressing Ctrl + Shift + B. Visual Studio Code should execute the build.sh script automatically.

Setup Debugging

Add the following Visual Studio Code specific files to the .vscode subdir:

.vscode/launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch (gdb)",
            "type": "cppdbg",
            "request": "launch",
            "cwd": "${workspaceFolder}",
            "linux": {
                "program": "${workspaceFolder}/build/debug/simple",
                "MIMode": "gdb"
            }
        }    
    ]
}

Test the debugging

Set a breakpoint on the first line of int main() inside src/main.cpp. Press F5 to launch the debugger. It should stop at the breakpoint.