您现在的位置是:首页 > 文章详情

c调用c++函数

日期:2019-01-21点击:587
  • c调用c++普通函数
    cpp_test/cpp.h

#ifndef CPP_H #define CPP_H #include "extern_cpp.h" int add(int a, int b); char add(char a, char b); #endif // CPP_H

    cpp_test/extern_cpp.h

#ifndef EXTERN_CPP_H #define EXTERN_CPP_H #ifdef __cplusplus extern "C" { #endif int add_int(int a, int b); char add_char(char a, char b); #ifdef __cplusplus } #endif #endif // EXTERN_CPP_H

    cpp_test/cpp.cpp

#include "cpp.h" #include <iostream> int add(int a, int b) { std::cout << "int a+b=" << a+b << std::endl; return a+b; } char add(char a, char b) { std::cout << "char a+b=" << a+b << std::endl; return a+b; } int add_int(int a, int b) { return add(a,b); } char add_char(char a, char b) { return add(a,b); }

    c_test/main.c

#include <stdio.h> #include "../cpp_test/extern_cpp.h" int main(int argc, char *argv[], char *env[]) { printf("%d\n", add_int(2,3)); printf("%c\n", add_char(20, 30)); return 0; }

编译 g++ -c cpp.cpp       
    gcc main.c ../cpp_test/cpp.o -lstdc++

  • c调用c++类函数
     cpp_test/cpp.h

#ifndef CPP_H #define CPP_H #include "extern_cpp.h" struct example { public: example(void); example(int i, int j); ~example(void); int add(void); int a,b; }; #endif // CPP_H

    cpp_test/extern_cpp.h

#ifndef EXTERN_CPP_H #define EXTERN_CPP_H #ifdef __cplusplus extern "C" { #endif typedef struct example example; example* exmaple_create(int a, int b); void example_delete(example* e); int example_add(example* e); #ifdef __cplusplus } #endif #endif // EXTERN_CPP_H

    cpp_test/cpp.cpp

#include "cpp.h" #include <iostream> example::example(void){} example::example(int i, int j):a(i),b(j){} example::~example(void){} int example::add(void) { std::cout << "a+b=" << a+b << std::endl; return a+b; } example* exmaple_create(int a, int b) { return new example(a, b); } void example_delete(example* e) { delete e; } int example_add(example* e) { return e->add(); }

    c_test/main.c
#include <stdio.h> #include "../cpp_test/extern_cpp.h" int main(int argc, char *argv[], char *env[]) { example *e = exmaple_create(2, 3); printf("%d\n", example_add(e)); example_delete(e); return 0; }
编译 g++ -c cpp.cpp

        gcc main.c ../cpp_test/cpp.o -lstdc++


原文链接:https://yq.aliyun.com/articles/688531
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章