在Linux系统上使用gcc编译C语言文件


在Linux上使用gcc来编译C文件

准备

新建项目文件夹

mkdir lab1

在文件夹里面创建并完成c文件

cd lab1
vim hello-world.c

Step 1: Preprocess(预处理)

gcc -E -o hello-world.i hello-world.c

预处理器展开预处理指令,也就是任何以 "#"开头的行。这些指令在你的代码编译之前就会被处理。

运行上面的命令,看看预处理后的文件hello-world.i;你会看到一堆东西,然后是你的代码(在最后)。

Step 2: Compile(编译)

gcc -S -o hello-world.s hello-world.i

然后,编译器将预处理后的C代码翻译成汇编语言。

Step 3: Assemble(汇编)

as -o hello-world.o hello-world.s

汇编器接收汇编语言文件hello-world.s,并输出一个对象文件helloworld.o。

objdump -t hello-world.o

继续运行这个,汇编器输出一个文件,其中包含符号和机器代码。要查看该文件的符号表(记住,这是一个二进制文件,所以不能用文本编辑器打开它),请使用objdump。

Step 4: Link(链接)

gcc -o hello-world -l c hello-world.o

“-l c” which means “link with the standard C library”
链接器将多个对象文件合并成一个包,包括系统上运行的许多不同程序共享的对象文件,也就是所谓的库。运行上面的命令,会将hello-world.o与需要运行的对象文件链接起来,生成可执行的二进制文件 “hello-world”

Step 5: Load(加载)

ldd hello-world

它告诉你当可执行文件运行时,哪些库会被加载到内存中。

Step 6: Execute(执行)

./hello-world

程序可以是一个路径(包含斜线),也可以只是一个程序的名称(不包含 斜杠)。当你只是执行一个程序的名称时,操作系统通过标准位置搜索二进制文件(如/usr/bin),去找到这个名称的程序。默认情况下,大多数系统不会搜索当前的工作目录(一般来说是件好事,因为你不希望意外地执行一些不好的程序) ,所以你需要提供一个路径(带斜线的东西)来执行一个程序,由于这个程序不在标准位置。添加./通常是最简单的方法。如果你的当前所在路径到父目录,你可以这样:

lab1/hello-world

gcc选项解释

gcc -g -std=c99 -Wall -Werror -o output-executable -l library1 [-l library2] … input-file1.c [input-file2.c] …

  • -g means compile with debugging symbols.
  • -std=c99 means use the ANSI 1999 C standard.
  • -Wall means warn about all possible problems with your code.
  • -Werror means fail if there are any warnings.
  • -o output-executable indicates that the program to be built should be called output-executable
  • -l library means link with library at the linking stage
  • input-file1.c input-file2.c are the inputs files implementing your program, written in C

快速编译执行

gcc -g -std=c99 -Wall -Werror -o hello-world hello-world.c

  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值