标签:
/** * kaflog4c.h */ #include <stdio.h> #include <stdlib.h> void hello(const char *msg);
/** * kaflog4c.c */ #include "kaflog4c.h" void hello(const char *msg) { printf("Hello %s!\n", msg); }
$ gcc -W -Wall -fPIC -ansi -pedantic -I. -c kaflog4c.c $ gcc -shared kaflog4c.o -o libkaflog4c.so
$ ar r libkaflog4c.a kaflog4c.o
编译要产生链接到动态库(libkaflog4c.so)的程序和静态库(libkaflog4c.a)的程序
/** * main.c */ #include "kaflog4c.h" int main () { hello("cheungmine"); return 0; }
$ gcc -W -Wall -ansi -pedantic -I. -c main.c $ gcc main.o -o main ./libkaflog4c.so # 查看依赖 $ ldd ./main # 运行 $ ./main
$ gcc main.o -o main ./libkaflog4c.a $ ldd ./main # 此时删除libkaflog4c.a和libkaflog4c.so对下面的执行无影响 $ ./main
/** * main_dl.c */ #include "kaflog4c.h" #include <dlfcn.h> void dl_hello() { void *dp; void (*fn_hello)(const char*); dp = dlopen("libkaflog4c.so", RTLD_LAZY); if (!dp) { printf("%s\n", dlerror()); exit(1); } fn_hello = dlsym(dp, "hello"); if (!fn_hello) { printf("%s\n", dlerror()); exit(1); } fn_hello("cheungmine: load library when running"); dlclose(dp); } int main() { dl_hello(); return 0; }
(libkaflog4c.so已经存在于当前目录下)
$ gcc -W -Wall -ansi -I. -c main_dl.c $ gcc main_dl.o -o main_dl -ldl $ ldd main_dl $ ./main_dl $ sudo mv ./libkaflog4c.so /usr/local/lib/ $ ./main_dl libkaflog4c.so: cannot open shared object file: No such file or directory $ sudo ldconfig $ ./main_dl
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/ubuntu64fan/article/details/49718531