How to fix ROS2 undefined reference to rclcpp::init
Problem
You are trying to compile a C++ executable using rclcpp
, but during the linking phase you see error messages such as
/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()'
Solution
Generally this means that you didnt configure your build system correctly. By default, ROS2 expects you to let ROS2 (and its CMake macros) handle the linking of your executables.
Check out our post about index-symbols.py
which contains a script to find the required libraries for any missing symbol.
However, in case you want to manually link your executables, you need to add the following to your CMakeLists.txt
:
target_link_libraries(your_executable_name rclcpp)
Replace your_executable_name
with the name of your executable target.
In case you see an new error message like
/usr/bin/ld: cannot find -lrclcpp: No such file or directory
you might need to add the path to the ROS2 libraries to your CMakeLists.txt
:
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