c调用c++函数

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值