linux系统的库文件的创建和链接

来源:互联网 发布:社区app软件 编辑:程序博客网 时间:2024/05/16 12:46


创建目录及文件结构如下:

├── include│   └── hello.h├── lib│   └── hello.c└── src    └── main.c

其中:

源文件hello.h:

#include <stdio.h>void hello(){  printf("hello world!\n");}


头文件:

#ifndef _HELLO_H_#define _HELLO_H_void hello();#endif

main.c文件:

#include "hello.h"int main(){ hello();}


编译静态库函数:

  

cd srcgcc -c hello.car -rc libhello.a hello.o

ar命令将hello.o添加到静态库文件libhello.a,ar命令就是用来创建、修改库的,也可以从库中提出单个模块,参数r表示在库中插入或者替换模块,c表示创建一个库



链接静态库:

gcc main.c -o hello -L../lib -lhello -I../include


创建动态库:

gcc -o libhello.so hello.c -shared -fPIC -I../include

链接动态库:

gcc main.c -o hello -L../lib -lhello -I../include

设置环境变量:

export LD_LIBRARY_PATH=../lib

运行:

./hello

输出:

hello world!


















0 0