Create a ROS 2 package (C++)


Software in ROS 2 is organized in packages. The goal of these packages is to provide useful functionality. Take into account that the packages should be functionality, but not too much than other software can use it. A ROS 2 package is simply a directory.

This tutorial show how to create a ROS 2 package in C++. For considering a valid package must meet a few requirements

  • The package should contain a file named package.xml
    • Provides meta information about the package
  • The package should contain a file named CMakeLists.txt
    • Provide information about the package and dependencies

A ROS 2 package have the next structure:

C++:

src/
    my_package/
        CMakeLists.txt
        package.xml

cd ~/ros2_ws/src/ros2
mkdir testpackagecpp
cd testpackagecpp

Checkout the name label. Should be named as the folder

cmake_minimum_required(VERSION 2.8.3)

project(testpackagecpp)

if(NOT WIN32)
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Wextra")
endif()

find_package(ament_cmake REQUIRED)
find_package(example_interfaces REQUIRED)
find_package(rcl REQUIRED)
find_package(rmw REQUIRED)
#find_package(rmw_implementation REQUIRED)
#force opensplice implementation
find_package(rmw_opensplice_cpp REQUIRED)
#find_package(rmw_fastrtps_cpp REQUIRED)

ament_package()

Checkout the name label. Should be named as the folder

<?xml version="1.0"?>
<package format="2">
  <name>testpackagecpp</name>
  <version>0.0.0</version>
  <description>Package containing examples of how to use the rcl API.</description>
  <maintainer email="ahcorde@erlerobot.org">Alejandro Hernandez</maintainer>
  <license>Apache License 2.0</license>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <buildtool_depend>rosidl_default_generators</buildtool_depend>

  <build_depend>example_interfaces</build_depend>
  <build_depend>rcl</build_depend>
  <build_depend>rmw_implementation</build_depend>

  <exec_depend>example_interfaces</exec_depend>
  <exec_depend>rcl</exec_depend>
  <exec_depend>rmw_implementation</exec_depend>
  <exec_depend>rosidl_default_runtime</exec_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

With this command you are going to build only the package: testpackagecpp

cd ~/ros2_ws
ament build --symlink-install --only-package testpackagecpp

Do you need more computing capacity in your robots? Stay tuned