C语言—动态库建立

来源:互联网 发布:淘宝的评价管理在哪里 编辑:程序博客网 时间:2024/06/08 06:26

一. 动态库的书写

头文件test.h:

#ifdef   TEST_H
#define  TEST_H
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b);
int Less(int a ,int b);
#endif

实现文件test.c:
#include "test.h"
int add(int a,int b){
        return  a+b;
}
int Less(int a,int b){
        return  a-b;
}
         

二、编译动态库

gcc tes.c -fPIC -shared -o libtest.so    //如果有多个.c 文件,就把所有的.c文件进行编译

隐式链接(编译时链接)
使用gcc main.c -L. -ltest -o test进行编译。
-L:添加库文件的搜索路径
-l:指定需要链接的库。该名称是处在头lib和后缀.so中的名称,如上动态库libtest.so的l参数为-l test

在执行隐式链接的程序之前要注意设置LD_LIBRARY_PATH环境变量,或者把前面生成的libtest.so复制到系统路径下,否则会找不到动态库。
$ ./test
./test: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
$ export LD_LIBRARY_PATH=.
$ ./test

或者把编译好的动态库放到/usr/lib 中去



1 0
原创粉丝点击