0 运行环境
-
本机系统:Windows 7
-
虚拟机软件:Oracle VM VirtualBox 6
-
虚拟机系统:CentOS 7
1 GCC 简介
GCC 是 GUN Compiler Collection的缩写,可以支持多种语言编译,比如 C,C++,Java,pascal 等。
2 GCC 常用选项
-
-o:生成目标
-
-E:激活预处理。生成预处理文件( .i 文件)
-
-S:激活预处理、编译。生成汇编代码( .s 文件)
-
-c:激活预处理、编译、汇编。生成目标文件( .o 文件)
-
-Wall:打开编译警告
-
-g:包含调试信息
-
-llib:链接 lib 库
-
-I:指定头文件目录
-
-Idir:增加 include 目录(头文件路径)
-
-LDir:增加 lib 目录(编译静态库和动态库)
3 GCC 编译
3.0 示例代码
示例程序如下:
//hello.c
#include <stdio.h>
int main(void)
{
printf("Hello World!
");
return 0;
}
vim 编辑器中的代码:
当前所在的位置:
3.1 四个过程
3.1.1 预处理
编译器将 C 源代码中的包含的头文件如stdio.h编译进来,替换宏。
gcc -E hello.c -o hello.i
3.1.2 编译
GCC 首先要检查代码的规范性、是否有语法错误等,以确定代码的实际要做的工作,在检查无误后,GCC 把代码翻译成汇编语言。
gcc –S hello.i –o hello.s
3.1.3 汇编
把编译阶段生成的 ”.s” 文件转成二进制目标代码。
gcc –c hello.s –o hello.o
3.1.4 链接
链接到库中,生成可执行文件。
gcc hello.o –o hello
3.2 一次性完成
输入命令 gcc hello.c -o hello
,如下图所示:
运行编译后的可执行程序 ./hello
,如下图所示:
4 多个文件的编译方法
现在有 3 个文件,分别是 main.c,print.c,print.h
main.c 如下所示:
// main.c
#include "print.h"
int main(void)
{
print();
return 0;
}
print.c 如下所示:
// print.c
#include <stdio.h>
void print(void)
{
printf("you have done well !
");
}
print.h 如下所示:
// print.h
void print();
4.1 假如头文件和源文件都在一个目录下
4.1.1 多个文件一起编译
在 shell 中输入:
gcc print.c main.c -o main_print
如下所示:
4.1.2 分别编译各个源文件,再对编译后输出的目标文件(.o)链接
在 shell 中输入:
gcc -c print.c -o print.o
gcc -c main.c -o main.o
gcc print.o main.o -o main_print
如下所示:
4.2 假如头文件和源文件不在一个目录下
源文件所在目录:
头文件在 myInclude 目录下:
在 shell 中输入,主要是要加 -I 指定头文件目录
gcc print.c main.c -o main_print -I myInclude
运行截图:
5 GCC 参数详解
GCC 参数详解 - 菜鸟教程 - https://www.runoob.com/w3cnote/gcc-parameter-detail.html