C和C++混编1

假设有下面这样三个文件:

/* file: test_extern_c.h */ 
#ifndef   __TEST_EXTERN_C_H__
#define __TEST_EXTERN_C_H__ 
#ifdef __cplusplus 
extern "C" { 
#endif 
extern int ThisIsTest(int a, int b); 

#ifdef __cplusplus 

}

#endif /* end of __cplusplus */ 

#endif


在这个头文件中只定义了一个函数,ThisIsTest()。这个函数被定义为一个外部函数,可以被包括到其它程序文件中。假设ThisIsTest()函数的实现位于test_extern_c.c文件中: 
/* test_extern_c.c */

#include "test_extern_c.h" 
int ThisIsTest(int a, int b) 

return (a + b); 
}


可以看到,ThisIsTest()函数的实现非常简单,就是将两个参数的相加结果返回而已。现在,假设要从CPP中调用ThisIsTest()函数:

/* main.cpp */

#include "test_extern_c.h" 

#include <stdio.h> 
#include <stdlib.h> 
class FOO { 
public: 
int bar(int a, int b) 

printf("result=%i\n", ThisIsTest(a, b)); 

};

int main(int argc, char **argv) 

int a = atoi(argv[1]); 
int b = atoi(argv[2]); 
FOO *foo = new FOO();

foo->bar(a, b); 
return(0); 
}

在这个CPP源文件中,定义了一个简单的类FOO,在其成员函数bar()中调用了ThisIsTest()函数。下面看一下如果采用gcc编译test_extern_c.c,而采用g++编译main.cpp并与test_extern_c.o连接:

 gcc -c test_extern_c.c 
       g++ main.cpp test_extern_c.o 
     ./a.out 4 5 
result=9

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值