Skip to main content

Code Autoformatting in VSCode

To use the autoformatting in VSCode, follow these steps:

  1. Install VSCode
  2. Install VSCode extensions: C/C++, C/C++ Extension Pack, clangd, Run on Save (VSCode might prompt you to disable intelliSenseEngine, do it)
  3. Set up clangd config for C/C++ code formatting: create file $HOME/.clang-format in your gome directory and paste the above content inside
  4. Set up clangd as the default formatter: File -> Preferences -> Settings and set Editor: Default Formatter to clangd.
  5. Set up code formatting on save: File -> Preferences -> Settings and check Editor: Format on Save.

Now when you save a file (Ctrl + s), you code should automatically reformat. However, clangd requires file compile_commands.json generated by cmake run with CMAKE_EXPORT_COMPILE_COMMANDS=ON. In our setup, this is done automatically when colcon build is run, but one compile_commands.json is generated for each ROS package in workspace/build/_package_/compile_commands.json. The following setup process links the workspace/build/_package_/compile_commands.json into the relevant ROS package whenever the package is built. The package-specific compile_commands.json is then loaded by clangd.

  1. In the ROS2 package, open .gitignore and add the following line, if you don't have it in your .global_gitignore
compile_commands.json
  1. In the ROS2 package, open CMakeLists.txt and add the following lines right after the project(you_project_name) (this will create and link a compile_commands.json file in the package source dir after every colcon build)
# --- Export & Symlink compile_commands.json ---
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(SOURCE_JSON "${CMAKE_SOURCE_DIR}/compile_commands.json")
set(BINARY_JSON "${CMAKE_BINARY_DIR}/compile_commands.json")

if(EXISTS ${BINARY_JSON} AND NOT EXISTS ${SOURCE_JSON})
message(STATUS "Symlinking compile_commands.json to source directory")
execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink ${BINARY_JSON} ${SOURCE_JSON})
endif()
  1. Open the ROS2 package in VSCode.
  2. Code formatting shall work for you now. You may verify that by changing ColumnLimit: 50 in $HOME/.clang-format, saving a file, and checking that each row has max. 50 characters. Revert this change back to ColumnLimit: 160 afterwards.

We recommend opening a ROS2 package not from the workspace symlink, but from the source of your ~/git folder.