C语言的编译与调试
1.编译软件
gcc 编译C语言的
g++ 编译C++语言的
2.gcc与g++编译选项
-ggdb -ggdblevel 为调试器 gdb生成调试信息。Jevel可以为1,2,3,默认值为2。 -o outfile输出到指定的文件 -E仅作预处理(code.i,不进行编译、汇编和链接。 -g-glevel 生成操作系统本地格式的调试信息。-g和-ggdb汇编和链接并不太相同,-g会生成gdb 之外的信息。level取值同上。 -S仅编译到汇编语言(code.s),不进行汇编与链接 -c编译、江编到目标代码(code.o),不进行链接。 -shared生成共享目标文件。通常用在建立共享库时。 -Wall会打开一些很有用的警告选项,建议编译时故加此选项。 -static禁止使用共享连接 -w 禁止显示所有警告信息。 -llibrary进行链接时搜索名为library的库 -ldir 把dir加入到搜索头文件的路径列表 -Ldir 把dir 加入到搜索库文件的路径列表中。 例子:$ goo-l/homel/foo-L/home/foo -ltest test.c-o test -Dname 预定义一个名为name的宏,值为1。 例子:$ gcc -DTEST_CONFIG test.c -o test -Dname =definition 预定义名为name,值为definition的宏。 Optimization -O0禁止编译器进行优化。默认为此项。 -O -O1尝试优化编译时间和可执行文件大小。 -O2更多的优化,会尝试几乎全部的优化功能,但不会进行“空间换时间”的优化方法。 -O3在O2的基础上再打开一些优化选项:-finline-functions, -funswitch-loops和 -fgcse-after-reload . -Os对生成文件太小进行优化。它会打开-O2开的全部选项,除了会那些增加文件大小的。
2. 多文件编译脚本
Makefile的规则
日标:需要的条件
命令(注意前面用tab键开头)
解释:
1目标可以是一个或多个,可以是Object File,也可以是执行文件,甚至可以是一个标签
2需要的条件就是生成目标所需要的文件或目标
3命令就是生成目标所需要执行的脚本,比如gcc,g+t, rm等
脚本示例
hello:main.o func.o g++ -g -o hello main.o func.o main.o:main.cpp g++ -g -c main.cpp -o main.o func.o:func.cpp g++ -g -c func.cpp -o func.o clean: rm -f *.o hello
3.调试
安装gdb,注意编译的时候,编译选项选上-g,否则pdb会报Reading symbols from /home/test/hello...(no debugging symbols found)...done.
gdb hello List b-break for func,line r-run c-continue s-step into n-step over p-print q-quit 多线程 gdp -p pid set scheduler-locking on info threads thread 2 b functionname c/s/n objdump -S hello查看汇编代码
core文件调试
生成CORE文件并调试CORE文件: 查看系统CORE文件设置:ulimit -a 打开CORE文件:ulimit -c unlimited 或者ulimit -c 1000 禁用:ulimit -c O 调试CORE文件: gdb programbin corefile
示例:
关键源码:
int *i = NULL;
*i = 80;
cout<<i<<endl;
gdb ./hello core.34084(其中的core.34084是程序崩溃的时候产生的文件)
输出
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-120.el7
Copyright (C) 2013 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-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/test/hello...done.
BFD: Warning: /home/test/core.34084 is truncated: expected core file size >= 413696, found: 110592.
[New LWP 34084]
Cannot access memory at address 0x7faebba9f128
Cannot access memory at address 0x7faebba9f120
Failed to read a valid object file image from memory.
Core was generated by `./hello'.
Program terminated with signal 11, Segmentation fault.
#0 0x0000000000400c56 in main () at main.cpp:6
6 *i = 80
上述core配置只是临时作用的,想要永久生成CORE文件,需要配置到/etc/profile中的: ulimit -c unlimited ulimit -S -c 0 >/dev/null 2>&1. source /etc/profile

浙公网安备 33010602011771号