linux动态链接库创建和使用

预备知识:

  如何找到生成的动态库有3种方式:

  1)把库拷贝到/usr/lib和/lib目录下。

  (2)在LD_LIBRARY_PATH环境变量中加上库所在路径。

  例如动态库libhello.so在/home/example/lib目录下:

  $export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/example/lib

  (3) 修改/etc/ld.so.conf文件,把库所在的路径加到文件末尾,并执行ldconfig刷新。这样,加入的目录下的所有库文件都可见。

  当静态库和动态库同名时, gcc命令将优先使用动态库。

        2)创建静态库:ar cr libmyhello.a hello.o

        3)创建动态库:gcc -shared -fPCI -o libmyhello.so hello.o

1、动态库的头文件:my_lib_fucntions.h,注意到头文件extern "C"{}的使用

/*experiment:create dynamic library*/
#include <stdio.h>
#ifndef MY_LIB_FUCNTION_HEADER
#define MY_LIB_FUCNTION_HEADER
#ifdef _cplusplus
extern "C" {
#endif
void printHello();
#ifdef _cplusplus
}
int add(int x,int y);
#endif
#endif

2、动态库函数实现:my_lib_fucntions.c

#include "my_lib_functions.h"
void printHello(){
    printf("hello,qw!\n");
}
int add(int x,int y){
    return x+y;
}

3、编写测试程序:my_lib_test.c

#include "my_lib_functions.h"
#include <stdio.h>
int main(void){
    printHello();
    printf("1+1 = %d\n",add(1,1));
}

4、编写一个脚本来自动执行(当前库和执行文件都在当前路径下):program:my_lib_test.sh

unset LD_LIBRARY_PATH

export LD_LIBRARY_PATH=.
gcc -fpic -shared -o libmyfunction.so my_lib_functions.c
gcc -o my_lib_test my_lib_test.c -lmyfunction -L`pwd`
./my_lib_test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值