C++程序调用C函数

这种需求很多,又因为C++和C是两种完全不同的编译链接处理方式,所以要稍加处理.总结大致有两大类实现方法.

文中给出的是完整的,具体的,但又最基本最简单的实现,至于理论性的东西在网上很容易搜索的到.

 

一.通过处理被调用的C头文件

a.h:

#ifndef __A_H
#define __A_H

#ifdef __cplusplus
extern "C" {
#endif

int ThisIsTest(int a, int b);

#ifdef __cplusplus
}
#endif

#endif

 

a.c:

#include "a.h"

int ThisIsTest(int a, int b) {
  return (a + b);
}

 

aa.h:

class AA {
  public:
      int bar(int a, int b);
};

 

aa.cpp:

#include "a.h"
#include "aa.h"
#include "stdio.h"

int AA::bar(int a, int b){
    printf("result=%d/n", ThisIsTest(a, b));
    return 0;
}

 

main.cpp:

#include "aa.h"

int main(int argc, char **argv){
  int a = 1;
  int b = 2;
  AA* aa = new AA();
  aa->bar(a, b);
  delete(aa);
  return(0);
}

 

Makefile:

all:
        gcc -Wall -c a.c -o a.o
        gcc -Wall -c aa.cpp -o aa.o
        gcc -Wall -c main.cpp -o main.o
        g++ -o test *.o

 

 

二. 通过处理调用的C++文件

恢复a.h文件为一般性C头文件,在aa.cpp文件中extern包含a.h头文件或函数.

a.h:

#ifndef __A_H
#define __A_H
int ThisIsTest(int a, int b);
#endif

 

aa.cpp:

extern "C"
{
    #include "a.h"
}
#include "aa.h"
#include "stdio.h"

int AA::bar(int a, int b){
    printf("result=%d/n", ThisIsTest(a, b));
    return 0;
}

 

or

 

aa.cpp:

#include "aa.h"
#include "stdio.h"

extern "C"
{
    int ThisIsTest(int a, int b);
}

int AA::bar(int a, int b){
    printf("result=%d/n", ThisIsTest(a, b));
    return 0;
}

 

 

 

 

 

 

 

 

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值