Create ROS2 pkg for C++ and Python files

Sachin Kumar
2 min readFeb 27, 2021

--

Photo by Alex Knight on Unsplash

The Robot Operating System (ROS) is a set of software libraries and tools for building robot applications. From drivers to state-of-the-art algorithms, and with powerful developer tools, ROS has what you need for your next robotics project. And it’s all open source.

ROS2 is the next version of ROS which provides more features and deals with limitations from the previous version. ROS2 provides three types of build-depends as ament_cmake, ament_python, and cmake.

Recently I was working on a ROS2 project in which I was using ROS2 python to create the node. In this, I need to create a custom ROS2 msg-type. I searched for the tutorials and documents to create custom msgs in the ros2 pkg with build type ament_python.

But I didn’t find any way to build a custom msg in the python build type pkg.

So, to solve this problem, I created a new pkg in ros2 with build_type ament_cmake to build the custom messages. That’s how I solved the problem.

But that is not all. This is not how it should work. We can need to find a way to build the msgs, c++ files, and even python scripts. Luckily, I found this and will share the process.

  1. Create a ros2 pkg inside your colcon_ws
$ ros2 create pkg my_ros2_pkg --build-type --ament-cmake

2. Build the pkg

$ colcon build

3. Create a custom msg

Make a folder msg in the ros2 pkg and add file Num.msg

int64 num

4. Create a Publisher in C++ in src

make a file ros2_publisher.cpp in the src folder

5. Create a subscriber in Python in scripts

create a folder named same as pkg e.g. my_ros2_pkg and inside this folder create a file __init__.py and add the files you want to use as modules

make a file ros2_subscriber.py in the folder scripts

6. Modify package.xml

7. Modify CMakeList.xml

8. Test ros2 publisher node, subscriber node and custom msg

Publisher

Subscriber

ROS2 custom msg Num

That’s all! For ros2 pkg that can build custom msgs and srvs and even build C++ file with includes and Python scripts with modules. ❤️

--

--