预备知识:
如何找到生成的动态库有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