chenbrian
about   posts   tags   github  

ROS2 LSP Setup

TLDR: you want code completions while working with ROS2

LSP with clangd

ROS2 puts its headers into /opt/ros2/<ROS_DISTRO>/include. This doesn’t work out of the box with my fairly default clangd setup, and it would be too easy if it just worked out of the box with vim! Most editors like vscode or clion have their own way of handling scenarios like this, e.g. vscode using a c_cpp_properties.json file.

For vscode setup, see this or this

With vim this is as little uglier. Nothing that clang supports using either a compile_commands.json file or a compile_flags.txt file source, we can either:

Method 0: Colcon mixins compile_commands

As it turns out there are colcon mixins, though the use of which is not exactly well documented. Steps for use are as follows:

  1. Install the python3-colcon-mixin package; sudo apt install python3-colcon-mixin, or pip install colcon-mixin
  2. Fetch the ‘default’ colcon mixins:
  3. Add the default mixins file:
1
   colcon mixin add default https://raw.githubusercontent.com/colcon/colcon-mixin-repository/master/index.yaml
  1. Fetch them: colcon mixin update default
  2. Use them: colcon build --mixin compile-commands

And this will work out of the box to generate the relevant compile_commands.json files.

Method 1: CMake

Generate a compile_commands file using colcon build --cmake-args -DCMAKE_EXPORT_COMPILE_COMMANDS=ON It’s also probably prudent to add this to your CMakeLists.txt file anyways,

1
2
3
4
5
6
7
# CMakeLists.txt

# This should work
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# ... but if it doesn't, try this workaround
set(CMAKE_EXPORT_COMPILE_COMMANDS ON CACHE INTERNAL "")

Note that this requires there to be a buildable ros2 package in your workspace, so if one is just getting started maybe try cloning the ros2_tutorials package or copy-pasting a simple pub-sub just to get a compile_commands.json file.

Method 2: Bear

Try using bear which works great in my experience, i.e. bear -- colcon build

Method 3: compile_flags.txt

Place a compile_flags.txt file with -I /opt/ros2/<ROS_DISTRO>/include in your project root

For more, see this

METHOD 4: manually create a compile_commands.json file

If all else fails, try dropping in a minimal compile_commands.json file with the following contents, making sure to edit the filepaths accordingly:

1
2
3
4
5
6
// compile_commands.json
[ {
  "directory": "<YOUR_ROS2_WORKSPACE>/src/build/<YOUR_ROS2_PACKAGE",
  "command": "/usr/bin/c++ -DDEFAULT_RMW_IMPLEMENTATION=rmw_fastrtps_cpp -DRCUTILS_ENABLE_FAULT_INJECTION -DSPDLOG_COMPILED_LIB -isystem /opt/ros2/foxy/include -Wall -Wextra -Wpedantic -std=gnu++14 -o CMakeFiles/<YOUR_PACKAGE_NAME>.dir/src/<YOUR_FILE_NAME>.o -c <YOUR_ROS2_WORKSPACE>/src/<YOUR_ROS2_PACKAGE>/src/<YOUR_FILE_NAME>.cpp",
  "file": "<YOUR_ROS2_WORKSPACE>/src/<YOUR_ROS2_PACKAGE>/src/<YOUR_FILE_NAME>.cpp"
} ]