Writing a Node by using ROS2 Cpp Client Libraries.

Create a package

Navigate into the workspace directory

1
ros2 pkg create --build-type ament_cmake [package_name]

Write the code

Navigate into [workspace_directory]/src/[cpp_package_name]/src

write the node code using your preferred text editor.

Add dependencies

Navigate into the package directory.

Open the file named package.xml .

Add <depend>package_name</depend> after the ament_cmake buildtool dependency.

Modify the CMakeLists

Open the CMakeLists.txt file. Below the existing dependency find_package(ament_cmake REQUIRED), add the linesfind_package(package_name REQUIRED)

After that, add the executable and name it node_name so you can run your node using ros2 run:

1
2
add_executable([node_name] src/[node_function].cpp)
ament_target_dependencies([node_name] [dependencies_package_names ...])

Finally, add the install(TARGETS…) section so ros2 run can find your executable:

1
2
3
install(TARGETS
node_name
DESTINATION lib/${PROJECT_NAME})

Build and run

Navigate into the workspace directory

Run rosdep in the root of your workspace to check for missing dependencies before building.

1
2
3
rosdep update
and
rosdep install -i --from-path src --rosdistro foxy -y

Still in the root of the workspace, build the package.

1
colcon build --packages-select [package_name]

or build all packages in the workspace.

1
colcon build

Source the setup files.

1
. install/setup.bash

Now run the node.

1
ros2 run [package_name] [node_name]