Reusing Code in ROS2 Projects: Creating a Python Submodule in a C++ or Python Common Package

In ROS2 projects, it’s often useful to store boilerplate code in a «common» package to reuse across multiple parts of your project. Your common package can be a Python package or a C++ package if you wish to be flexible with C++ and Python.

To do this, follow these steps:

  1. Edit CMakeLists.txt for C++ packages: Add the following line for a submodule named your_package_name_lib:

    ament_python_install_package(${PROJECT_NAME}_lib)

    Place this line before ament_package(). This command installs the Python package located in the ${PROJECT_NAME}_lib directory, where ${PROJECT_NAME} is your project name.
  2. Edit setup.py for Python Packages: If you prefer to handle this in a purely Python package, modify setup.py as follows:

    from setuptools import setup


    setup( name='your_project_name',
    version='0.1.0',
    packages=['your_project_name_lib'],
    install_requires=[ # List of dependencies ]
    )