本文共 2102 字,大约阅读时间需要 7 分钟。
#ifndef CPP_H#define CPP_H#include "extern_cpp.h"int add(int a, int b);char add(char a, char b);#endif // CPP_Hcpp_test/extern_cpp.h
#ifndef EXTERN_CPP_H#define EXTERN_CPP_H#ifdef __cplusplusextern "C"{#endifint add_int(int a, int b);char add_char(char a, char b);#ifdef __cplusplus}#endif#endif // EXTERN_CPP_H
#include "cpp.h"#includec_test/main.cint 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);}
#include编译 g++ -c cpp.cpp#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;}
#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_Hcpp_test/extern_cpp.h
#ifndef EXTERN_CPP_H#define EXTERN_CPP_H#ifdef __cplusplusextern "C" {#endiftypedef 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
#include "cpp.h"#includec_test/main.cexample::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();}
#include#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;}
gcc main.c ../cpp_test/cpp.o -lstdc++
转载地址:http://chmjl.baihongyu.com/