GCC编译流程
GCC(GNU Compiler Collection)编译流程主要分为四个步骤:
这里一一个测试程序lab2_1为例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PAGESIZE 4096
#define MAX_SIZE 100*PAGESIZE
int main(){
char *buf = (char*)malloc(MAX_SIZE);
memset(buf, 0, MAX_SIZE);
printf("buffer address=0x%p\n", buf);
free(buf);
return 0;
}
预处理(Pre-Process)
Pre-Process之后成为 *.i
编译命令为:arm-linux-gnueabi-gcc -E test.c -o test.i
...
extern void *malloc (size_t __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) ;
...
int main(){
char *buf = (char*)malloc(100*4096);
memset(buf, 0, 100*4096);
printf("buffer address=0x%p\n", buf);
free(buf);
return 0;
}
编译(Compile)
Compile之后成为 *.s
编译命令为:arm-linux-gnueabi-gcc -S test.i -o test.s
这一步生成了汇编代码
.arch armv5t
.fpu softvfp
.eabi_attribute 20, 1
.eabi_attribute 21, 1
.eabi_attribute 23, 3
.eabi_attribute 24, 1
.eabi_attribute 25, 1
.eabi_attribute 26, 2
.eabi_attribute 30, 6
.eabi_attribute 34, 0
.eabi_attribute 18, 4
.file "lab2_1.c"
.section .rodata
.align 2
.LC0:
.ascii "buffer address=0x%p\012\000"
.text
.align 2
.global main
.syntax unified
.arm
.type main, %function
main:
@ args = 0, pretend = 0, frame = 8
@ frame_needed = 1, uses_anonymous_args = 0
push {fp, lr}
add fp, sp, #4
sub sp, sp, #8
mov r0, #409600
bl malloc
mov r3, r0
str r3, [fp, #-8]
mov r2, #409600
mov r1, #0
ldr r0, [fp, #-8]
bl memset
ldr r1, [fp, #-8]
ldr r0, .L3
bl printf
ldr r0, [fp, #-8]
bl free
mov r3, #0
mov r0, r3
sub sp, fp, #4
@ sp needed
pop {fp, pc}
.L4:
.align 2
.L3:
.word .LC0
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 5.5.0-12ubuntu1) 5.5.0 20171010"
.section .note.GNU-stack,"",%progbits
汇编(Assemble)
Assemble之后成为 *.o(二进制文件)
编译命令为:arm-linux-gnueabi-gcc -c test.s -o test.o
链接(Link)
将生成的test.o与一些c语言表在库文件链接起来,生成可执行文件
编译命令为:arm-linux-gnueabi-gcc test.o -o test --static
动态链接库是 *.so 静态链接库是 *.a,
默认使用的是动态链接库,加了–static则使用静态链接库
附: Makefile文件
cc = arm-linux-gnueabi-gcc
prom = lab2_1
obj = lab2_1.o
CFLAGS = -static
$(prom): $(obj)
$(cc) -o $(prom) $(obj) $(CFLAGS)
%.o: %.c
$(cc) -c $< -o $@
clean:
rm -rf $(obj) $(prom)
tips:
% 表示通配符
$@ 表示目标
$< 表示第1个依赖文件
$^ 表示所有依赖文件
当想生成a.o文件时发现与%.o : %.c匹配,则将%替换为a,也就是a.o : a.c,则会执行规则的命令。