C调用C++库
核心参数:-Xlinker -rpath=PATH
类似于linux 中 export LD_LIBRARY_PATH=PATH,将库的路径写进程序,当运行程序是自动会改地址找库
例子:
├── cpp_file
│ ├── test.cpp
│ ├── test.h
│ └── test_head.h
└── main.c
cpp_file/test.cpp
#include <iostream>
#include "test.h"
using namespace std;
int hello()
{
cout<<"hello world"<<endl;
return 0;
}
cpp_file/test.h
#ifndef TEST_H
#define TEST_H
#ifdef __cplusplus //当使用C++编译器编译*.cpp和*.h文件的时候,extern "C" 生效
extern "C" {
#endif
int hello();
#ifdef __cplusplus
}
#endif
#endif
cpp_file/test_head.h
#ifndef TEST_HEAD_H
#define TEST_HEAD_H
extern int hello();
#endif
编译成动态库
g++ test.cpp -shared -o libtest.so -fPIC -Xlinker -rpath=./
main.c
#include "stdio.h"
#include "cpp_file/test_head.h"
int main()
{
hello();
return -1;
}
编译
gcc main.c -o main -I ./ -ltest -L cpp_file -Xlinker -rpath=./cpp_file
-Xlinker -rpath=./cpp_file 告知程序运行时取./cpp_file处找库,不用与-L,-L是链接时找库路径
运行
./main
hello world
使用ldd 查看库依赖
linux-vdso.so.1 (0x00007fff6b59e000)
libtest.so => ./cpp_file/libtest.so (0x00007f67a4a40000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f67a464f000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f67a42c6000)
/lib64/ld-linux-x86-64.so.2 (0x00007f67a4e44000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f67a3f28000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f67a3d10000)
发现libtest.so => ./cpp_file/libtest.so 需要libtest.so时去一个相对路径找,所以即使整个项目移动后也能正常运行