gcc的基本使用
在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