本实例是最简化的实现模板,一个头文件hello.h及其C++实现hello.cpp,另外就是C代码main.c,来调用hello.cpp实现的函数.
#ifndef H_HELLO
#define H_HELLO
#ifdef __cplusplus
extern "C" {
#endif
int getAge();
int getCount();
#ifdef __cplusplus
}
#endif
#endif
#include <iostream>
#include "hello.h"
int getAge() {
std::cout << "get age" << std::endl;
return 99;
}
int getCount() {
std::cout << "get count" << std::endl;
return 123456;
}
编译为动态链接库
g++ -fPIC -shared -o libhello.so hello.cpp
include <stdio.h>
#include "hello.h"
int main() {
int age = getAge();
int count = getCount();
printf("%d:%d\n", age, count);
return 0;
}
gcc main.c -L. -lhello -o main
main: main.c libhello.so
gcc main.c -L. -lhello -o main
libhello.so: hello.cpp
g++ -fPIC -shared -o libhello.so hello.cpp
clean:
rm -f *.o *.so main
至此,已经实现了C代码调用C++自定义库函数
#include <iostream>
#include "hello.h"
int main() {
int age = getAge();
std::cout << age << ":" << getCount() << std::endl;
return 0;
}
g++ main.cpp -L. -lhello -o main
可以看出,C++、C代码可以共享函数getAge(), getCount()
如果对你有一点帮助,麻烦为我点一个赞,如果没有帮助,也非常期待你的反馈
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有