First install gdb and xterm
sudo apt install xterm
Ubuntu systems generally come with gdb by default. Use gdb -v to see if there is any output. If there is a version output, it has been installed and there is no need to install it again.
sudo apt install gdb
Enable compilation options
To use Debug debugging, you first need to add the debug option when compiling the program to let cmake compile in debug mode. Otherwise, there will be no gdb debugging information, and you will not be able to view the source code and set breakpoints.
If you use the command line catkin_make, add a parameter when entering catkin_make:
catkin_make -DCMAKE_BUILD_TYPE=Debug
Or modify CMakelist.txt directly and add the following code:
SET(CMAKE_BUILD_TYPE "Debug")
SET(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")
SET(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall")
Debugging method
One is to debug coredump files, and the other is to debug online.
Online debugging is mostly used, and online debugging is divided into roslaunch debugging and rosrun node debugging.
Add GDB debugging instructions to the launch file
Modify the ROS launch file and add parameters in the node tag
launch-prefix="xterm -e gdb -ex run --args"
example:
<launch>
<node pkg="learning_topic" type="person_subscriber" name="talker" output="screen" launch-prefix="xterm -e gdb -ex run --args"/>
<node pkg="learning_topic" type="person_publisher" name="listener" output="screen" />
</launch>
Run as follows:
Debugging using rosrun node
rosrun --prefix 'gdb -ex run --args' [package_name] [node_name]
running result:
Practical application:
/**
* 该例程将发布/person_info话题,自定义消息类型learning_topic::Person
*/
#include <ros/ros.h>
#include "learning_topic/Person.h"
int main(int argc, char **argv){
ros::init(argc, argv, "person_publisher789");// ROS节点初始化
ros::NodeHandle n;// 创建节点句柄
// 创建一个Publisher,发布名为/person_info的topic,消息类型为learning_topic::Person,队列长度10
ros::Publisher person_info_pub = n.advertise<learning_topic::Person>("/person_info/huati", 10);
ros::Rate loop_rate(1);// 设置循环的频率
int count = 0;
while (ros::ok()){
// 初始化learning_topic::Person类型的消息
learning_topic::Person person_msg;
person_msg.name = "Tom";
person_msg.age = 18;
person_msg.sex = learning_topic::Person::male;
person_info_pub.publish(person_msg);// 发布消息
ROS_INFO("Publish Person Info: name:%s age:%d sex:%d", person_msg.name.c_str(), person_msg.age, person_msg.sex);
//这里故意插入会引起段错误,导致程序崩溃的代码,看看gdb会输出什么
int *b = 0;
*b = 10;
loop_rate.sleep();// 按照循环频率延时
}
return 0;
}
Directly use the rosrun node node to start gdb for debugging. It is found that the error is on line 26, indicating that there may be incorrect syntax here.
You can also run the executable file directly for debugging:
gdb person_publisher
The result of pointing out the error is the same.
More references .