gcc编译动态链接库

来源:互联网 发布:asp.net crm源码 编辑:程序博客网 时间:2024/05/01 02:40

演示动态链接库的编译和使用

1. 编写代码

*************hello.h**************

void print_hello();

***********hello.c**************
#include "hello.h"#include <stdio.h>void print_hello(){    printf("hello world!");}
2. 编译生成动态链接库

gcc -fpic -shared hello.c -o libhello.so

-fpic: generate position-independent-code

-shared: generate a shared object which can then be linked with other objects to form an executable.

3. 将hello.h libhello.so文件放入特定目录
    如/home/test/local/include/ 和 /home/test/local/lib/下

4. 使用动态链接库

************test.c**************
#include <hello.h>int main(){    print_hello();}

编译链接
gcc test.c -o test -L/home/test/local/lib -lhello -I/home/test/local/include

-L:(Library)指定库文件目录
-I:(include)指定头文件目录

-l:(library)指定链接库

执行

./test

此时可能遇到"无法找到libhello.so"的错误, 这个问题是ld在加载动态库文件的时候,没有在搜索目录中找到libhello.so
一个解决方法是指定LD_LIBRARY_PATH

export LD_LIBRARY_PATH=/home/test/local/lib:$LD_LIBRARY_PATH

你的反馈就是博主进步的最大动力


原创粉丝点击