如何修复 ROS2 undefined reference to rclcpp::init
问题
你正在尝试使用 rclcpp 编译 C++ 可执行文件,但在链接阶段你看到如下错误消息
rclcpp-linker-error.txt
/usr/bin/ld: main.cpp:(.text+0x7b): undefined reference to `rclcpp::InitOptions::InitOptions(rcutils_allocator_s)'
/usr/bin/ld: main.cpp:(.text+0x9c): undefined reference to `rclcpp::init(int, char const* const*, rclcpp::InitOptions const&, rclcpp::SignalHandlerOptions)'
/usr/bin/ld: main.cpp:(.text+0xa8): undefined reference to `rclcpp::InitOptions::~InitOptions()'
/usr/bin/ld: main.cpp:(.text+0xdf): undefined reference to `rclcpp::spin(std::shared_ptr<rclcpp::Node>)'
/usr/bin/ld: main.cpp:(.text+0x145): undefined reference to `rclcpp::shutdown(std::shared_ptr<rclcpp::Context>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
/usr/bin/ld: main.cpp:(.text+0x1b1): undefined reference to `rclcpp::InitOptions::~InitOptions()'解决方案
通常这意味着你没有正确配置构建系统。默认情况下,ROS2 期望你让 ROS2(及其 CMake 宏)处理可执行文件的链接。
查看我们关于 index-symbols.py 的文章,其中包含一个脚本用于查找任何缺失符号所需的库。
但是,如果你想手动链接可执行文件,你需要在 CMakeLists.txt 中添加以下内容:
CMakeLists-link-rclcpp.patch
target_link_libraries(your_executable_name rclcpp)将 your_executable_name 替换为你的可执行目标名称。
如果你看到新的错误消息,如
ld-cannot-find-lrclcpp.txt
/usr/bin/ld: cannot find -lrclcpp: No such file or directory你可能需要在 CMakeLists.txt 中添加 ROS2 库的路径:
CMakeLists-add-libdir-rclcpp.patch
target_link_directories(your_executable_name PUBLIC /opt/ros/jazzy/lib/)If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow