C代码调用C++函数

本实例是最简化的实现模板,一个头文件hello.h及其C++实现hello.cpp,另外就是C代码main.c,来调用hello.cpp实现的函数.

hello.h

#ifndef H_HELLO
#define H_HELLO
#ifdef __cplusplus
extern "C" {
#endif
int getAge();
int getCount();
#ifdef __cplusplus
}
#endif
#endif

hello.cpp

#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

main.c

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

makefile自动化

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++自定义库函数

验证混合调用

main.cpp

#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()

注意事项

  • __cplusplus前面是两个下划线

如果对你有一点帮助,麻烦为我点一个赞,如果没有帮助,也非常期待你的反馈

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容