Quantcast
Channel: C++博客-Snow_斯诺-随笔分类-C/C++通用
Viewing all articles
Browse latest Browse all 7

在C代码中调用C++接口

$
0
0
一 在C源文件中调用C++封装的接口

例如:

要想在A.c文件中,调用生命在B.h,实现在B.cpp中的接口bool getMAC(char *mac_addr);

其实现方法 B.cpp 如下:
 1 // B.cpp
 2 
 3 #ifndef _cplusplus
 4 #define _cplusplus
 5 #endif
 6 
 7 #include <stdio.h>
 8 
 9 bool getMAC(char *mac_addr)
10 {
11     // your code
12 
13 }

B.h 头文件的声明为:

 1 // B.h
 2 
 3 #ifndef _B_H
 4 #define _B_H
 5 
 6 #ifdef __cplusplus    //__cplusplus是cpp中自定义的一个宏
 7 extern "C" {          //告诉编译器,这部分代码按C语言的格式进行编译,而不是C++的
 8 #endif
 9 
10 bool getMAC(char *mac_addr);
11 
12 #ifdef __cplusplus
13 }
14 #endif 
15 
16 #endif

A.c 中正常调用即可

 1 // A.c 
 2 
 3 #include "B.h"
 4 #include <stdio.h>
 5 
 6 int main()
 7 {
 8     bool bRet = false;
 9     char chMac[16] = {0};
10 
11     bRet = getMAC(chMac);
12 
13     return 0;
14 }


zhiye 2016-03-10 15:16 发表评论

Viewing all articles
Browse latest Browse all 7

Latest Images

Trending Articles





Latest Images