Products
96SEO 2025-09-20 13:56 0
在CentOS系统中,需先确保安装了GCC编译器和GDB调试器。可通过以下命令一键安装:
# 安装GCC编译器及基础开发工具
sudo yum groupinstall "Development Tools"
# 安装GDB调试器
sudo yum install gdb
安装完成后可是否安装成功。
使用GCC编译C/C++程序时 必须添加-g
选项,该选项会在生成的可施行文件中嵌入源代码的符号信息,这是GDB调试的基础。
示例:
gcc -g -o test
注意若未添加-g
选项, GDB将无法显示源代码或定位变量,调试功能将受限。
通过GDB加载编译好的可施行文件, 启动调试会话:
gdb ./test
启动后GDB会显示版本信息及程序入口,此时可输入调试命令。
调试过程中,常用命令如下:
#include
int main {
int a = 5;
int b = 10;
int c = a + b;
printf;
return 0;
}
gcc -g -o test
gdb ./test
break main
Breakpoint 1 at 0x400536: file , line 5.
run
Starting program: /root/test
Breakpoint 1, main at :5
5 int a = 5;
step
6 int b = 10;
print a
$1 = 5
continue
The sum of a and b is: 15
quit
run
启动程序。next
单步施行程序。step
进入函数内部施行。print
打印变量值。break
设置断点。continue
继续施行程序。quit
退出GDB调试器。若需要使用特定版本的GCC, 可通过Devtoolset安装新版本GCC,并切换环境:
# 安装Devtoolset
wget http:///tru/devtools-11/devtools- -O /etc/yum.repos.d/devtoolset-11.repo
sudo yum -y --enablerepo=devtools-11-devtools-11 install devtoolset-11-gcc devtoolset-11-gcc-c++
# 启用Devtoolset环境
source /opt/rh/devtoolset-11/enable
# 验证GCC版本
gcc --version
# 应显示devtoolset-11的GCC版本
# 使用devtoolset-X-gcc代替gcc编译程序
使用Devtoolset切换GCC版本后可以使用devtoolset-X-gcc
代替gcc
编译程序。
本文详细介绍了在CentOS下使用GCC调试程序的步骤, 包括安装GCC与GDB工具链、使用GDB调试器以及使用Devtoolset切换GCC版本。希望对您有所帮助。
Demand feedback