欢迎光临散文网 会员登陆 & 注册

GCC 和 GDB 的基本知识

2023-05-24 20:38 作者:卢朓  | 我要投稿

# GCC & GDB

作者: 北大王修远
---

- 安装
 
  - ubuntu:sudo apt install gcc
 
  - windows:mingw[Welcome to MinGW.OSDN](http://mingw.osdn.io/index.html)

- 官方文档:[Top (Using the GNU Compiler Collection (GCC))](https://gcc.gnu.org/onlinedocs/gcc/)

- 编译流程
 
    ![](编译流程.jpg)
 
  1. 预处理(preprocessing):去注释、头文件包含、宏替换、条件编译
     -E 选项指示编译器仅对输入文件进行预处理(.i文件)
 
  2. 编译(compilation)
     -S 选项产生汇编语言文件(.s文件)
 
  3. 汇编(assembly)
     -c 选项编译为机器语言的目标代码(.o文件)
 
  4. 链接(link)(可执行文件)
     
     -l 指定单个库文件, -L指定库文件目录

- 帮助:gcc --help, man gcc

- 常用编译选项
 
  - -o \<filename>
 
  - -D\<macro>
 
  - 编译标准:[C Dialect Options (Using the GNU Compiler Collection (GCC))](https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html)
    
    - -ansi(对于C等价于 -std=c90;对于C++等价于-std=c++98)
    
    - -std=    //c99_c11.c
 
  - 警告:[Warning Options (Using the GNU Compiler Collection (GCC))](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html)
    
    - -Wall:全部警告 //wall.c
    
    - -Wextra, -Werror
 
  - 优化:[Optimize Options (Using the GNU Compiler Collection (GCC))](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html)
    
    - -O0, -O1, -O2, -O3 //fibonacci.c
    
    - -Ofast:在-O3的基础上进一步优化,不严格按照标准
    
    - -Os: 最优化文件大小,开启所有一般不增加文件大小的-O2选项,并额外执行一些优化代码大小的选项。
      
      - -Oz:优化文件大小,相对于-Os更加激进,可能降低速度
 
  - -g:生成gdb符号表[Debugging Options (Using the GNU Compiler Collection (GCC))](https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html)
    
    - Og:debug优化

- 完整编译选项列表参见[Top (Using the GNU Compiler Collection (GCC))](https://gcc.gnu.org/onlinedocs/gcc/)

---

GDB

- 帮助:help,man gdb, [Top (Debugging with GDB) (sourceware.org)](https://sourceware.org/gdb/current/onlinedocs/gdb.html/)

- 使用:gdb <filename>

- 命令:
 
  - 显示:
    
    - l(list): 显示指定行号或者指定函数附近的代码   
      
      - set listsize
      - show listsize
    
    - p(print): 显示变量或表达式的值
    
    - disp(display): 把一个表达式设置为display,当程序每次停下来时都会显示其值
    
    - i(info): 显示各种信息,如i b显示所有断点, i disp 显示display,i lo显示所有局部变量
 
  - 断点:
    
    - b(break): 在指定行号或者指定函数开头处设置断点
      
      - cond 条件断点 e.g. cond 2 i==5
      
      - watch \<var>,awatch(读写), rwatch(读)
      
      - 编译器可能会优化掉某些行,此时使用-O0 //code.cpp -Og; b 77
    
    - cl(clear): 取消断点,和b的格式相同,如果该位置有多个断点将同时取消
    
    - d(delete): 取消指定编号的断点,若不指定编号则删除所有断点
 
  - 运行:
    
    - r(run): 运行程序,直到程序结束或者遇到断点而停下
    
    - c(continue): 在程序中断后继续执行程序,直到程序结束或者遇到断点而停下。在程序开始执行前只能用r,不能用c
    
    - n(next): 执行一条语句,如果有函数调用,则把它作为一个整体
    
    - s(step): 执行一条语句,如果有函数调用,则进入函数内部
    
    - u(until): 执行到指定行号或者指定函数的开头
 
  - q(quit)

GCC 和 GDB 的基本知识的评论 (共 条)

分享到微博请遵守国家法律