linux环境下编译工具链GCC的使用总结
1.编译
gcc、g++分别是gnu系列下c和c++编译器。
sudo apt install gcc gdb #安装gcc和gdb
gcc -v #查看gcc的版本信息
源文件 -------> 可执行文件要经过四个步骤:
(.c + .h) 预处理 -> .i (预处理之后的代码)
.i 编译 -> .s (汇编代码)
.s 汇编 -> .o(将汇编代码翻译成机器可识别的二进制目标文件)
多个.o + 库文件 链接 -> 可执行文件
对应gcc命令如下:
gcc -E hello.c -o hello.i #生成预处理后的文件
gcc -S hello.i -o hello.s #生成汇编代码
gcc -c hello.s -o hello.o #生成目标文件
gcc hello.o -o hello #生成可执行文件
gcc的其他选项:
选项 | 含义 |
---|---|
-Dmacro | 相当于在文件开头添加了#define macro这个宏 |
-I | 指定头文件的搜索路径 |
-Wall | 生成所有警告信息 |
-O0,-O1,-O2,-O3 | 指定编译器的优化等级一般为-O1 |
-g | 编译时生成相应的调试信息(变量等等) |
调试
写程序难免遇到bug,这时候就需要GDB来对程序进行调试,调试需要在编译的时候,加上一些调试信息,即需要指定-g选项。
gcc hello.c -o hello -g
进入调试界面的方法:
gdb executable_name #不设置任何命令行参数
gdb --args executable_name [arg]...
#调试界面
yfg@yfg-Machine:~/cpp_50/linux05$ gdb text
GNU gdb (Ubuntu 8.1.1-0ubuntu1) 8.1.1
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from text...done.
(gdb)
ok,我们可以调试程序了
设置断点 break/b
(gdb) break 20 #在当前程序的20行设置断点
Breakpoint 1 at 0x684: file text.c, line 20.
(gdb) break main #在main函数处设置断点
Breakpoint 2 at 0x6df: file text.c, line 40.
(gdb) break main.c:44 #在源文件main.c44行处设置断点
No source file named main.c.
Make breakpoint pending on future shared library load? (y or [n]) n
(gdb) break main.c 10
Function "main.c 10" not defined.
Make breakpoint pending on future shared library load? (y or [n]) y
Breakpoint 3 (main.c 10) pending.
查看断点信息 info break
(gdb) info break #查看断点信息
#编号 类型 断点是否生效 断点在程序的位置
Num Type Disp Enb Address What
1 breakpoint keep y 0x0000000000000684 in sub at text.c:20
2 breakpoint keep y 0x00000000000006df in main at text.c:40
3 breakpoint keep y <PENDING> main.c 10
删除断点 delete/d [number] number:断点编号
gdb) delete 2 #删除标号为2的断点
(gdb) info break #再次查看断点信息
Num Type Disp Enb Address What
1 breakpoint keep y 0x0000000000000684 in sub at text.c:20
3 breakpoint keep y <PENDING> main.c 10
启动调试run
单步调试step
逐过程next/n
继续(去往逻辑上的下一个断点)continue/c
监视
1、使用print打印表达式的值[只能临时打印一次]
print EXP
使用print改变变量的值:
printf EXP=value
2.使用display命令自动展示表达式的值
display EXP #自动展示EXP
info display #显示所有自动展示的表达式信息
undisplay [n] #删除编号为[n]自动展示的表达式
(gdb) display r
(gdb) display PI*r*r
(gdb) info display
Auto-display expressions now in effect:
Num Enb Expression
1: y r
2: y PI*r*r
(gdb) undisplay 2
(gdb) undisplay
Delete all auto-display expressions? (y or n)
查看参数和临时标量的值
(gdb) info locals #查看函数的参数
(gdb) info args #查看所有局部变量的值