前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C代码调用C++函数

C代码调用C++函数

作者头像
十毛
发布2019-03-27 15:37:36
2.2K0
发布2019-03-27 15:37:36
举报
文章被收录于专栏:用户1337634的专栏

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

hello.h

代码语言:javascript
复制
#ifndef H_HELLO
#define H_HELLO
#ifdef __cplusplus
extern "C" {
#endif
int getAge();
int getCount();
#ifdef __cplusplus
}
#endif
#endif

hello.cpp

代码语言:javascript
复制
#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

代码语言:javascript
复制
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自动化

代码语言:javascript
复制
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

代码语言:javascript
复制
#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前面是两个下划线

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.07.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • hello.h
  • hello.cpp
  • main.c
  • makefile自动化
    • 验证混合调用
      • main.cpp
    • 注意事项
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档