Hey everyone π
In my previous blog, I shared how I started exploring ROS2 Humble using Turtlesim.
Now, Iβve moved one step ahead β by creating my own C++ node that publishes data inside ROS2.
This post will walk you through everything I did β step by step β so you can do the same on your system.
βοΈ Step 1:
Creating a New Package
- Inside your workspace:
cd ~/ros2_ws/src
ros2 pkg create --build-type ament_cmake pkg_2
What this does:
- Creates a folder named pkg_2
- Generates the necessary files: CMakeLists.txt, package.xml, include/, and src/
- Sets up a C++ ROS2 package ready for your node
Your structure should look like:
pkg_2/
βββ CMakeLists.txt
βββ include/pkg_2/
βββ package.xml
βββ src/
π§© Step 2:
Writing the Node
- Create a file:
cd pkg_2/src
nano my_node.cpp
This node doesnβt publish yet β but itβs alive and running, ready to communicate.
π Step 3:
Editing
CMakeLists.txt
This tells ROS2 how to compile your C++ node and link it with the rclcpp library
π¦ Step 4:
Updating package.xml
Open:
nano ../package.xml
And add your dependency to xml file:
<depend>rclcpp</depend>
ποΈ Step 5:
Building the Package
- Go back to your workspace:
cd ~/ros2_ws
colcon build
source install/setup.bash
colcon is the build tool front-end. It discovers packages in src/, figures out build order from package manifests, and runs the configured build tool (eg. ament_cmake) for each package. Results go into build/, install/, and log/.
Discovery
: colcon scans src/ for packages (reads package.xml).
βΆοΈ Step 6:
Running the Node
Run it with:
ros2 run pkg_2 my_node
Output:
[INFO] [my_cpp_node]: Hello guys this is nagu !
π Congratulations β youβve just created your first C++ ROS2 node!
Typical errors you might encounter and what they mean
Package
'pkg_2'not found:
You didnβtsource install/setup.bashof your workspace (or you built under a different overlay).
Linker errors (undefined references):
you forgot toament_target_dependencies(... rclcpp)orfind_package(rclcpp).
Runtime errors about DDS:
rclcpp::initcan fail if the rmw implementation is missing or environment variables are wrong. Also firewall settings can block DDS discovery.
It appears that the
colconcommand is not currently installed on your system. This tool is required to build ROS2 workspaces. You may install it using the following commands:
sudo apt update
sudo apt install python3-colcon-common-extensions -y
π¬ Whatβs Next?
In my next blog, Iβll extend this node to publish messages at regular intervals and create a subscriber node to receive them β this is where true ROS2 communication begins.
Stay tuned π
Until then, keep experimenting and exploring the power of ROS2!
π§© Bonus Tip:
To see all running nodes:
ros2 node list
To check logs:
ros2 topic echo /rosout
πͺΆ >Written by NARASIMHA ALIAS Nagu
π‘ "Don't prove, just improve."
follow me for more knowledge
Top comments (2)
this is good work
hi