使用 C 语言进行编译的简单实例
编写程序源代码
#include <stdio.h>
int main() {
printf("Hello World\n");
return 0;
}
开始编译和测试执行
在默认状态下,如果直接以 gcc 编译源码且未加任何参数,生成的执行文件默认为 a.out。
./a.out
生成目标文件与指定输出名
若需生成目标文件(object file)以便后续操作,或指定执行文件名而非默认的 a.out,可使用 -o 参数。
gcc -c hello.c -o hello.o
gcc hello.o -o hello
hello.o 为目标文件,再利用该文件制作出名为 hello 的执行文件。
多文件编译与链接
当源码文件不止一个时,无法直接一次性编译,通常先生成目标文件,再链接制成二进制可执行文件。
例如 thanks.c 调用了 thanks2.c 中的函数:
// thanks.c
void func();
int main() {
func();
return 0;
}
// thanks2.c
void func() {
// implementation
}
分别编译为独立的目标文件:
gcc -c thanks.c -o thanks.o
gcc -c thanks2.c -o thanks2.o
将两个目标文件链接成一个二进制可执行文件:
gcc thanks.o thanks2.o -o thanks
若更新 thanks.c,只需重新编译该文件生成新的 thanks.o,再链接即可,无需重新编译未修改的文件。
调用外部函数库
计算三角函数或指数函数需加入数学库。主程序调用 sin 函数,该函数位于 libm.so 中。编译时需显式链接该库。


