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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Bobsweetie/article/details/70148495


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

├── 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 src
gcc -c hello.c
ar -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!


















猜你喜欢

转载自blog.csdn.net/Bobsweetie/article/details/70148495