Open a CMake project in Visual Studio Code

This post shows how to open and build a CMake project in Visual Studio Code.

Install Extensions

When working with C/C++ and CMake I recommend to have at least the C/C++ Extension Pack and the CMake Language Support extensions installed. View this post on how to install extensions.

Open the project

To open the project, start VS Code and open the project root folder via File -> Open Folder or via terminal and inside the root folder enter:

code .

VS Code will start and will most likely prompt you if you trust the authors of this folder. If you do (e.g. this is all your code), click Yes. If you click No you will enter Restricted mode and some things will be disabled, including debugging and extensions.
Further information on Workspace Trust can be found here.

Scan for kits

After that you will have to scan for a kit to build your project.

Visual Studio Code - Scan for kits
Scan for kits.

If this does not open show up or disappeared, you can bring it up again, by going to the status bar at the bottom and click on No Kit Selected:

Visual Studio Code - Change the active kit
Change the active kit

Select one of you detected compilers (for me this is Clang 14.0.0 or GCC 11.2.0) and the status bar will change accordingly:

Visual Studio Code kit selected
GCC kit selected

Build the project

To build the project, check the status bar again:

Visual Studio Code - build selected target
Build selected target

The status bar tells us that we will use GCC 11.2.0 x86_64 to build the [Debug] configuration for [all] targets inside the project.

Change build configuration

To change from [Debug] to [Release] click the control and you can select a new configuration:

Visual Studio Code - Change build variant
Change Build variant

Build individual targets

To build individual targets click [all] in the status bar and you can choose from a list of targets inside your project.

Debug and run targets

You can select the targets to debug / run from within Visual Studio Code on the right of the debug / run icons:

Visual Studio Code - change executable to run and debug
Change executable to run / debug