目录文件
$ ls
hello.c hello.h libhello.so main main.c
hello.c
#include "hello.h"
void hello(void)
{
printf("show hello\r\n");
}
hello.h
#ifndef _HELLO_H_
#define _HELLO_H_
#include <stdio.h>
void hello(void);
#endif /* _HELLO_H_ */
生成动态链接库libhello.so
$ gcc hello.c -fPIC -shared -o libhello.so
main.c 内容
#include "hello.h"
int main(void)
{
hello();
return 0;
}
使用动态链接库生成执行文件main
gcc -o main main.c -L. -lhello
显示main的dependency,看到并没有找到libhello.so库 (libhello.so => not found)
$ ldd main
linux-vdso.so.1 => (0x00007ffdd9b68000)
libhello.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f36952a9000)
/lib64/ld-linux-x86-64.so.2 (0x00007f3695673000)
设置LD_LIBRARY_PATH,添加当前目录,这样就能找到libhello.so库了
$ export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
再次查看main的dependency:
$ ldd main
linux-vdso.so.1 => (0x00007ffdf385f000)
libhello.so => ./libhello.so (0x00007f41b875a000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f41b8390000)
/lib64/ld-linux-x86-64.so.2 (0x00007f41b895c000)
执行main
$ ./main
show hello