如何修复 ROS2 undefined reference to rosidl_message_type_support_t

问题

你正在尝试使用 rclcpp 编译 C++ 可执行文件,但在链接阶段你看到如下错误消息

ros2_undefined_reference_error.txt
/usr/bin/ld: CMakeFiles/my_rclcpp_node.dir/main.cpp.o: in function `rclcpp::Serialization<sensor_msgs::msg::JointState_<std::allocator<void> > >::Serialization()':
main.cpp:(.text._ZN6rclcpp13SerializationIN11sensor_msgs3msg11JointState_ISaIvEEEEC2Ev[_ZN6rclcpp13SerializationIN11sensor_msgs3msg11JointState_ISaIvEEEEC5Ev]+0x16): undefined reference to `rosidl_message_type_support_t const* rosidl_typesupport_cpp::get_message_type_support_handle<sensor_msgs::msg::JointState_<std::allocator<void> > >()'

解决方案

通常这意味着你没有正确配置构建系统。默认情况下,ROS2 期望你让 ROS2(及其 CMake 宏)处理可执行文件的链接。

但是,如果你想手动链接可执行文件,你需要在 CMakeLists.txt 中添加以下内容以链接所需的库。

注意,所需的库特定于你使用的消息,所以不仅仅是

rosidl_typesupport_cpp.txt
rosidl_typesupport_cpp::get_message_type_support_handle

而是

rosidl_typesupport_cpp_sensor_msgs.txt
rosidl_typesupport_cpp::get_message_type_support_handle<sensor_msgs::msg::JointState...

但是,通常你可以记住链接错误消息中的消息类型的库加上 __rosidl_typesupport_cpp

在这种情况下,消息来自 sensor_msgs,所以库名称是 sensor_msgs__rosidl_typesupport_cpp

查看我们关于 index-symbols.py 的文章,其中包含一个脚本用于查找任何缺失符号所需的库

CMakeLists_target_link_libraries.txt
target_link_libraries(your_executable_name sensor_msgs__rosidl_typesupport_cpp)

your_executable_name 替换为你的可执行目标名称。

如果你看到新的错误消息,如

ros2_undefined_reference_error_2.txt
/usr/bin/ld: cannot find -lsensor_msgs__rosidl_typesupport_cpp: No such file or directory

你可能需要在 CMakeLists.txt 中添加 ROS2 库的路径:

CMakeLists_target_link_directories.txt
target_link_directories(your_executable_name PUBLIC /opt/ros/jazzy/lib/)

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