Correctly using vscode for Cmake project

If You Use Vscode, Use CMake Extension Instead of c_cpp_properties.json

April 20, 2023
Very short guide why you use CMakeLists.txt for code completion

For Ubuntu users working with CMake projects and writing C++ code, it's important to set up Visual Studio Code (VSCode) correctly for smooth auto-completion and debugging.

Many of vscode users would use c_cpp_properties.json to make vscode find headers (opens in a new tab) during code completion (for the interested, checkout this tutorial (opens in a new tab)). But actually, this is not a good idea.

Pitfall of using c_cpp_properties.json

If we rely on c_cpp_properties.json, we are manually feeding header search paths to vscode. Although this works for code-completion, your project might not be built correctly. The reason is simple. Success of building process has nothing to do with vscode, and its supporter, c_cpp_properties.json, as compilers will use CMakeLists.txt for building, not the json file. (Consider you did not give anything how to compile your project in c_cpp_properties.json.)

Due to this, users might come across a mismatch between vscode and compilers. For example, although your vscode found no problems in your code, your CMake project cannot be built while not finding some headers.

CMakeLists.txt has everything we need to know

This is an example CMakeLists.txt (I brought this from my repo (opens in a new tab))

find_package(SimplePackage REQUIRED)
add_executable(client_project_executable main.cpp)
target_link_libraries(client_project_executable simple_package)

As you can see, this file actually has every information a compiler needs to know.

  • include_directories: which folders to include to search headers.
  • find_package: which package to read and where to find the libraries and headers of the packages.
  • target_link_libraries: which libraries to be linked.

So, if vscode can well-extract the information, it is nonsense that we cannot do code-completion for our CMake project!

Setup CMake extension for configure, build, and debug


You should install gcc, g++, gdb, and cmake. If not installed, do:

sudo apt-get install gcc g++ gdb cmake

How to use CMake extension

Fully leveraging CMakeLists.txt on vscode can be done by CMake extension (opens in a new tab). I uploaded on youtube how to setup the extension for configure, build, and debug 👍