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.
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:
- Install the
python3-colcon-mixinpackage;sudo apt install python3-colcon-mixin, orpip install colcon-mixin - Fetch the ‘default’
colconmixins: - Add the default mixins file:
|
|
- Fetch them:
colcon mixin update default - 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,
|
|
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:
|
|