CMakeLists to compile a ROS2 C++ application without using the ROS2 build system

The following CMakeLists.txt works for compiling a C++ application using some of the ROS2 libraries without using the ROS2 build system. This can be used to circumvent ROS2’s CMake auto-configuration or enforce specific custom options.

You might need to adjust the library and include directory list if some libraries are missing for your specific application.

cmake_minimum_required(VERSION 3.8)

# Define the project name and specify C++ standard
project(rclcpp_example_project)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Specify the source files
add_executable(my_ros2_test main.cpp)

target_include_directories(my_ros2_test PUBLIC
    /opt/ros/jazzy/include/rclcpp/
    /opt/ros/jazzy/include/rcl_interfaces/
    /opt/ros/jazzy/include/rosidl_runtime_c/
    /opt/ros/jazzy/include/rosidl_runtime_cpp/
    /opt/ros/jazzy/include/builtin_interfaces/
    /opt/ros/jazzy/include/rosidl_typesupport_interface/
    /opt/ros/jazzy/include/rosidl_dynamic_typesupport/
    /opt/ros/jazzy/include/rosidl_typesupport_introspection_cpp/
    /opt/ros/jazzy/include/rcutils/
    /opt/ros/jazzy/include/rcl/
    /opt/ros/jazzy/include/rmw/
    /opt/ros/jazzy/include/rcpputils/
    /opt/ros/jazzy/include/rcl_yaml_param_parser/
    /opt/ros/jazzy/include/type_description_interfaces/
    /opt/ros/jazzy/include/tracetools/
    /opt/ros/jazzy/include/libstatistics_collector/
    /opt/ros/jazzy/include/statistics_msgs/
    /opt/ros/jazzy/include/rosbag2_cpp/
    /opt/ros/jazzy/include/rosbag2_storage/
    /opt/ros/jazzy/include/service_msgs/
    /opt/ros/jazzy/include/sensor_msgs/
    /opt/ros/jazzy/include/std_msgs/
)

target_link_directories(my_ros2_test PUBLIC /opt/ros/jazzy/lib/)

target_link_libraries(my_ros2_test
  rclcpp
  rcl
  tracetools
  rmw_implementation
  rcutils
  rosbag2_cpp
  rosbag2_storage
  sensor_msgs__rosidl_typesupport_cpp
)

# Install the target
install(TARGETS my_ros2_test
  DESTINATION lib/${PROJECT_NAME}
)