GCC总结常用编译命令和常用内置函数。
1 GCC编译选项
1.1 GCC常用编译选项
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
file.c C语言源代码
file.i 预处理后的C语言源文件
file.s GUN汇编代码
file.o 链接文件
.a 归档库文件(Archive file)
-o file 指定生成的可执行文件的文件名为file
-c 编译或者汇编源代码,但是不执行链接操作;生成file.o文件
-E 对源文件进行预处理,得到的信息显示在stdin;一般重定位到某个文件中,例如:
gcc -E main.c > main.i
-g 在目标程序中加入调试信息,用于debug
-I 指定头文件所在的文件夹
-L 指定函数库所在的文件夹
-O 对编译代码进行优化,后跟优化级别。例如-O3
-S 将源代码编译为汇编代码;生成file.s文件
-std=standard standard,其中standard为C/C++的标准,例如c89,c99,c++0x,c++11
-Wall 打开所有警告信息
|
1.2 GCC的attribute功能
1.2.1 aligned
功能说明:该属性指定结构体变量或者变量的最小对齐长度,单位是字节。
示例:
1
|
int x __attribute__ ((aligned (16))) = 0;
|
1.2.2 packed
功能说明:该属性指定结构体变量或者变量的最小对齐长度:变量最小对齐长度为1字节,结构体变量的最少为1位,除非通过aligned属性执行最大值。
使用示例:
1
2
3
4
|
struct foo {
char a;
int x[2] __attribute__ ((packed));
};
|
1.2.3 section
attribute((section(“name”)))实现在编译时把某个函数/数据放到指定的内存区域。以下两种格式都是可以的。
1
2
|
__attribute__((__section__("section_name")))
__attribute__((section("section_name")))
|
使用示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
struct duart a __attribute__ ((section ("DUART_A"))) = { 0 };
struct duart b __attribute__ ((section ("DUART_B"))) = { 0 };
char stack[10000] __attribute__ ((section ("STACK"))) = { 0 };
int init_data __attribute__ ((section ("INITDATA"))) = 0;
int main()
{
/* Initialize stack pointer */
init_sp(stack + sizeof(stack));
/* Initialize initialized data */
memcpy(&init_data, &data, &edata - &data);
/* Turn on the serial ports */
init_duart(&a);
init_duart(&b);
}
|
参考文献:
GCC Specifying Attributes of Variables
2 gcc编译时使用asan的方法
- 环境安装和gcc版本对应的libasan版本。
- 编译代码时添加
-fsanitize=address参数。
例如:
1
|
gcc -Wall -g -std=c99 -fsanitize=address lru.c -o lru
|
备注:ubuntu系统中不同asan版本和gcc的对应关系。
- libasan0: gcc-4.8
- libasan2: gcc-5
- libasan3: gcc-6
- libasan4: gcc-7
- libasan5: gcc-8
3 GCC的