- 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++