Linux下C++调用C动态库使用
动态库编译
ShareLib1.h
#ifndef __SHARELIB1_H__
#define __SHARELIB1_H__
#ifdef __cplusplus
extern "C" {
#endif
void ShareLib1_Print();
#ifdef __cplusplus
}
#endif
#endif
ShareLib1.c
#include "ShareLib1.h"
#include<stdio.h>
void ShareLib1_Print()
{
printf("Share Lib Print 1\n");
}
编译动态库命令
code@code-VBox:~/code/unix/sharelib$ gcc ShareLib1.c -fPIC -shared -o libShareLib1.so
code@code-VBox:~/code/unix/sharelib$ ls
libShareLib1.so ShareLib1.c ShareLib1.h
动态库使用
C++调用C的动态库
main.cpp
#include"ShareLib1.h"
int main(void)
{
ShareLib1_Print();
return 0;
}
编译main.cpp
code@code-VBox:~/code/unix/sharelib$ g++ main.cpp -L. -lShareLib1
code@code-VBox:~/code/unix/sharelib$ ls
a.out libShareLib1.so main.cpp ShareLib1.c ShareLib1.h
此时直接执行./a.out会报错如下
code@code-VBox:~/code/unix/sharelib$ ./a.out
./a.out: error while loading shared libraries: libShareLib1.so: cannot open shared object file: No such file or directory
三种方法解决
-
将libShareLib1.so所在路径添加到LD_LIBRARY_PATH,然后再执行./a.out,该方法当当前窗口关闭后失效。
code@code-VBox:~/code/unix/sharelib$ export LD_LIBRARY_PATH=/home/code/code/unix/sharelib:$LD_LIBRARY_PATH code@code-VBox:~/code/unix/sharelib$ ./a.out Share Lib Print 1
-
将libShareLib1.so放到/usr/lib目录下
code@code-VBox:~/code/unix/sharelib$ sudo cp libShareLib1.so /usr/lib/ [sudo] password for code: code@code-VBox:~/code/unix/sharelib$ ./a.out Share Lib Print 1
-
将libShareLib1.so写到配置文件中
ShareLib1.conf
/home/code/code/unix/sharelib
将ShareLib1.conf放到lib config目录下,然后重新加载lib config。
code@code-VBox:~/code/unix/sharelib$ sudo mv ShareLib1.conf /etc/ld.so.conf.d
code@code-VBox:~/code/unix/sharelib$ sudo /sbin/ldconfig
code@code-VBox:~/code/unix/sharelib$ ./a.out
Share Lib Print 1