C调用C++编译的库

本文演示了如何在C程序中调用C++编译的库,重点讨论了链接器选项-L、-rpath和-rpath-link的区别,以及如何使用-Xlinker-rpath设置运行时库的查找路径。通过一个实例,展示了如何编译动态库和主程序,并确保程序在移动后仍能正确找到库文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C调用C++库

参考
C语言调用C++实现的库函数方法

-L、-rpath和-rpath-link的区别

核心参数:-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时去一个相对路径找,所以即使整个项目移动后也能正常运行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值