How to fix ROS2 'undefined reference to 'rosbag2_cpp::Writer::open()'
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: 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()'
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.
However, in case you want to manually link your executables, you need to add the following to your CMakeLists.txt
in order to link the required library librosbag2_cpp.so
via -lrosbag2_cpp
:
Check out our post about index-symbols.py
which contains a script to find the required libraries for any missing symbol.
target_link_libraries(your_executable_name librosbag2_cpp)
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 -lrosbag2_cpp: 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/)