不使用 ROS2 构建系统编译 ROS2 C++ 应用程序的 CMakeLists

以下 CMakeLists.txt 可用于在不使用 ROS2 构建系统的情况下编译使用某些 ROS2 库的 C++ 应用程序。这可用于绕过 ROS2 的 CMake 自动配置或强制执行特定的自定义选项。

如果你的特定应用程序缺少某些库,你可能需要调整库和包含目录列表。

CMakeLists-example.txt
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}
)

Check out similar posts by category: ROS, C/C++, CMake