如何修复 ROS2 'undefined reference to rosbag2_cpp::Writer::open()'

问题

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

rosbag2-link-error.txt
/usr/bin/ld: CMakeFiles/my_rclcpp_node.dir/main.cpp.o: in function `JointStateRecorder::JointStateRecorder()':
main.cpp:(.text._ZN18JointStateRecorderC2Ev[_ZN18JointStateRecorderC5Ev]+0x29c): undefined reference to `rosbag2_cpp::Writer::open(rosbag2_storage::StorageOptions const&, rosbag2_cpp::ConverterOptions const&)'
/usr/bin/ld: main.cpp:(.text._ZN18JointStateRecorderC2Ev[_ZN18JointStateRecorderC5Ev]+0x5a2): undefined reference to `rosbag2_cpp::Writer::create_topic(rosbag2_storage::TopicMetadata const&)'
/usr/bin/ld: CMakeFiles/my_rclcpp_node.dir/main.cpp.o: in function `JointStateRecorder::~JointStateRecorder()':
main.cpp:(.text._ZN18JointStateRecorderD2Ev[_ZN18JointStateRecorderD5Ev]+0x34): undefined reference to `rosbag2_cpp::Writer::close()'

解决方案

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

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

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

CMakeLists-link-rosbag2.patch
target_link_libraries(your_executable_name librosbag2_cpp)

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

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

ld-cannot-find-lrosbag2.txt
/usr/bin/ld: cannot find -lrosbag2_cpp: No such file or directory

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

CMakeLists-add-libdir-ros2.patch
target_link_directories(your_executable_name PUBLIC /opt/ros/jazzy/lib/)

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