首页 > 系统 > Linux > 正文

Linux下编译C文件的过程

2020-05-27 13:13:14
字体:
来源:转载
供稿:网友

 

1、首先,写一个简单的C源文件:HelloWorld

 

#include <stdio.h>int main(){ printf("/nHello World!/n/n"); return 0;}

 

 

2、下面是调用gcc命令编译HelloWorld.c的过程:

[root@localhost gcc_test]# ls -ltotal 4-rw-r--r-- 1 root root 78 Sep 11 00:17 HelloWorld.c

 

// gcc的-E选项,可以让编译器在预处理后停止,并输出预处理结果。[root@localhost gcc_test]# gcc -E HelloWorld.c -o step1.i

[root@localhost gcc_test]# ls -ltotal 24-rw-r--r-- 1 root root    78 Sep 11 00:17 HelloWorld.c-rw-r--r-- 1 root root 18020 Sep 11 00:22 step1.i

 

// gcc的-S选项,表示在生成汇编代码后停止,-o输出汇编代码文件。[root@localhost gcc_test]# gcc -S step1.i -o step2.s

[root@localhost gcc_test]# ls -ltotal 28-rw-r--r-- 1 root root    78 Sep 11 00:17 HelloWorld.c-rw-r--r-- 1 root root 18020 Sep 11 00:22 step1.i-rw-r--r-- 1 root root   454 Sep 11 00:22 step2.s

 

// gas汇编器负责将生成的汇编代码文件编译为目标文件[root@localhost gcc_test]# gcc -c step2.s -o step3.o

[root@localhost gcc_test]# ls -ltotal 32-rw-r--r-- 1 root root    78 Sep 11 00:17 HelloWorld.c-rw-r--r-- 1 root root 18020 Sep 11 00:22 step1.i-rw-r--r-- 1 root root   454 Sep 11 00:22 step2.s-rw-r--r-- 1 root root   880 Sep 11 00:23 step3.o

 

// gcc连接器,负责将程序的目标文件与所需的所有附加的目标文件连接起来,最终生成可执行文件。附加的目标文件包括静态连接库和动态连接库。[root@localhost gcc_test]# gcc step3.o -o step4_result

[root@localhost gcc_test]# ls -ltotal 40-rw-r--r-- 1 root root    78 Sep 11 00:17 HelloWorld.c-rw-r--r-- 1 root root 18020 Sep 11 00:22 step1.i-rw-r--r-- 1 root root   454 Sep 11 00:22 step2.s-rw-r--r-- 1 root root   880 Sep 11 00:23 step3.o-rwxr-xr-x 1 root root  4734 Sep 11 00:23 step4_result

 

// 执行可执行程序[root@localhost gcc_test]# ./step4_result Hello World![root@localhost gcc_test]#  

 

3、上述拆分的过程完全可以一步执行:

[root@localhost gcc_test]# gcc HelloWorld.c -o result[root@localhost gcc_test]# ls -ltotal 48-rw-r--r-- 1 root root    78 Sep 11 00:17 HelloWorld.c-rwxr-xr-x 1 root root  4734 Sep 11 00:39 result-rw-r--r-- 1 root root 18020 Sep 11 00:22 step1.i-rw-r--r-- 1 root root   454 Sep 11 00:22 step2.s-rw-r--r-- 1 root root   880 Sep 11 00:23 step3.o-rwxr-xr-x 1 root root  4734 Sep 11 00:23 step4_result[root@localhost gcc_test]# ./result Hello World![root@localhost gcc_test]# 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表