1.gcc -o hello.o hello.c

2.gcc -shared -fPCI -o libtest.so hello.o

"-shared": 属性为可共享文件

“-fPCI”: -fPIC 作用于编译阶段,告诉编译器产生与位置无关代码(Position-Independent Code), 则产生的代码中,没有绝对地址,全部使用相对地址,故而代码可以被加载器加载到内存的任意 位置,都可以正确的执行。这正是共享库所要求的,共享库被加载时,在内存的位置不是固定的。

"libtest.so": lib 为库文件前缀 test库文件自己起的名字 .SO为动库的文件后缀

3.将 libtest.so复制到 /usr/lib内

4. 编译main.c


注意:可执行文件内没有动态库拷贝,只要删除动态库,可执行文件就会报错找不到库文件;可执文件在执行的时候再动态调用动态库,所以效率会比静态库低, 但是可执行文件可以得到空间上的压缩;而静态库则空间上的膨胀;


//hello.h 头文件

#ifndef HELLO_H

 

#define HELLO_H

void hello(const char **);

#endif // end hello.h



 

 

//hello.c 函数实现文件

#include<stdio.h>

void hello(const char **str)

{

printf("string:%s\n",*str);

}



 

 


//main.c 主程序文件

#include"hello.h"

int main(void)

{

const char *pstr = "hello world";

hello(&pstr);


return 0;

}