代码文件
hello.h
#include <stdio.h>
#include <stdlib.h>
void hello();
void main();
hello.c
#include "hello.h"
void hello()
{
printf("this is in hello...\n");
}
void main()
{
printf("main \n");
}
一 简单编译
gcc hello.c -o hello
直接经过了预处理、编译、汇编和链接
二 分步拆解
1,预处理
gcc -E hello.c -o hello.i
预处理结果就是将stdio.h 文件中的内容插入到hello.c中了
2,编译
gcc -S hello.i -o hello.s
gcc的-S选项,表示在程序编译期间,在生成汇编代码后,停止,-o输出汇编代码文件。
3,汇编
gcc -c hello.s -o hello.o
4,链接
gcc hello.o -o test
gcc连接器是gas提供的,负责将程序的目标文件与所需的所有附加的目标文件连接起来,最终生成可执行文件。附加的目标文件包括静态连接库和动态连接库
三 库文件链接
去掉原始文件main相关内容
#include "hello.h"
int main()
{
hello();
return 0;
}
1,生成库文件
gcc hello.c -shared -fPIC -o libhello.so
-shared选项说明编译成的文件为动态链接库,不使用该选项相当于可执行文件
-fPIC 表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的。所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正代码段共享的目的
2,
gcc hello_b.c -L ./ -l hello -o hello
其中-L ./ 表示链接的文件在当前目录下
-lhello 代表链接的文件名 gcc会自动为其前面添加lib,在其后边添加.so 即libhello.so
3,设置lib库文件地址
export LD_LIBRARY_PATH=/home/work/code/gcc/:$LD_LIBRARY_PATH