extern 关键字的使用

1、C++代码调用 非系统的 C 的头文件
需要包含#include行中的extern “C” {/* ... */}构造,这告诉C + +编译器在头文件中声明的函数是C函数。
extern "C" { // 拿到声明 f(int i, char c, float x) #include "my-C-code.h" } int main() { f(7, 'x', 3.14); ... }
2、C 代码 调用C++的函数
C++代码
Test.h文件:

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

Test.cpp 文件

#include "Test.h"

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

C代码

#include<stdio.h>

extern int Add(int a, int b);

int main() {  printf("%d\n",Add(3,5));  return 0; }

注意:C代码中不能有#include "Test.h" ,否则会编译失败。

posted @ 2013-04-01 22:27  礪劒  阅读(121)  评论(0)    收藏  举报