Wednesday 19 February 2020

Building C++ application on Ubuntu with CMake, make and VSCode

This article shows how to set up building C++ project with CMake and make in VSCode on Ubuntu.

First make sure cmake and make are installed:

$ cmake --version
cmake version 3.10.2
CMake suite maintained and supported by Kitware (

$ make --version
GNU Make 4.1
Built for x86_64-pc-linux-gnu
Copyright (C) 1988-2014 Free Software Foundation, Inc.
Licence GPLv3+: GNU GPL version 3 or later <>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Let's assume we have a C++ project with following structure:


build is an empty directory; this is where the build output will be located.


#include <iostream>

int main() {
    std::cout << "main()" << std::endl;
    return 0;


cmake_minimum_required(VERSION 3.0)
set(SOURCE src/main.cpp)
add_executable(${PROJECT_NAME} ${SOURCE})

In VSCode, press CTRL+SHIFT+P or go to View >> Command Palette, select Tasks: Configure Default Build Task and then Create tasks.json file from template and then Other.

VSCode - Configure Default Build Task
VSCode - Command Palette

This will create ./.vscode/tasks.json with a sample task:

    // See
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
            "label": "echo",
            "type": "shell",
            "command": "echo Hello"

We can replace it with cmake and make toolchain:

    // See
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
            "type": "shell",
            "label": "CMake && make",
            "options": {
                "cwd": "${workspaceFolder}/build"
            "command": "cmake make -DCMAKE_BUILD_TYPE=Debug .. && make -j 4",
            "group": {
                "kind": "build",
                "isDefault": true

To build a project press CTRL+SHIFT+B or go to Terminal >> Run Build Task.

We'd get the output like this:

> Executing task: cmake make -DCMAKE_BUILD_TYPE=Debug .. && make -j 4 <

-- Configuring done
-- Generating done
-- Build files have been written to: /home/xxxxxxx/xx/xxx/cmake-demo/build
Scanning dependencies of target cmake-demo
[ 50%] Building CXX object CMakeFiles/cmake-demo.dir/src/main.cpp.o
[100%] Linking CXX executable cmake-demo
[100%] Built target cmake-demo

Terminal will be reused by tasks, press any key to close it.

To run the executable (build output):

$ ./build/cmake-demo 


What is a CMake generator? - Stack Overflow
Ubuntu Manpage: cmake-generators - CMake Generators Reference
cmake(1) — CMake 3.5.2 Documentation
Visual Studio Code Setup for Beginners using C++ and CMake
C++ Development using Visual Studio Code, CMake and LLDB
How to compile C++ code with VS Code, CMake and NMake - 40tude
GCC and Make - A Tutorial on how to compile, link and build C/C++ applications
c++ - How does CMake choose gcc and g++ for compiling? - Stack Overflow

No comments: