Code Autoformatting in VSCode
To use the autoformatting in VSCode, follow these steps:
- Install VSCode
- Install VSCode extensions:
C/C++,C/C++ Extension Pack,clangd,Run on Save(VSCode might prompt you to disable intelliSenseEngine, do it) - Set up
clangdconfig for C/C++ code formatting: create file$HOME/.clang-formatin your gome directory and paste the above content inside - Set up
clangdas the default formatter:File -> Preferences -> Settingsand setEditor: Default Formattertoclangd. - Set up code formatting on save:
File -> Preferences -> Settingsand checkEditor: 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.
- In the ROS2 package, open
.gitignoreand add the following line, if you don't have it in your.global_gitignore
compile_commands.json
- In the ROS2 package, open
CMakeLists.txtand add the following lines right after theproject(you_project_name)(this will create and link acompile_commands.jsonfile in the package source dir after everycolcon 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()
- Open the ROS2 package in VSCode.
- Code formatting shall work for you now. You may verify that by changing
ColumnLimit: 50in$HOME/.clang-format, saving a file, and checking that each row has max. 50 characters. Revert this change back toColumnLimit: 160afterwards.
We recommend opening a ROS2 package not from the workspace symlink, but from the source of your ~/git folder.