extern "C" 包含双重含义,从字面上即可得到:首先,被它修饰的目标是“extern”的;其次,被它修饰的目标是“C”的。
1,被extern "C"限定的函数或变量是extern类型的:这说明该变量的范围是全局的,不局限于本源文件,可以被其他模块引用。注意与static 进行对比,static 修饰变量或者函数使得该变量或者函数的范围局限在该源文件。
2,被extern "C"修饰的变量和函数是按照C语言方式编译和连接的; 如果未加extern “C”声明时的编译方式,则会按照C++中的方式对变量和函数的编译链接。
注意:extern "C" 只能用于 C++中,不能用于C中。也就是说,extern "C"如果放在头文件中,那么该头文件是不能被C源程序包含的。
下面看一个例子:
1,被extern "C"限定的函数或变量是extern类型的:这说明该变量的范围是全局的,不局限于本源文件,可以被其他模块引用。注意与static 进行对比,static 修饰变量或者函数使得该变量或者函数的范围局限在该源文件。
2,被extern "C"修饰的变量和函数是按照C语言方式编译和连接的; 如果未加extern “C”声明时的编译方式,则会按照C++中的方式对变量和函数的编译链接。
注意:extern "C" 只能用于 C++中,不能用于C中。也就是说,extern "C"如果放在头文件中,那么该头文件是不能被C源程序包含的。
下面看一个例子:
C语言中引用C++中的函数
//Header.h
#ifndef C_PLUS_PLUS_H
extern "C" int plus(int x,int y); //指明按C语言的方式进行编译链接
#endif C_PLUS_PLUS_H
//source.cpp
#include "Header.h"
int plus(int x,int y){
return x + y;
}
//test.c
#include <stdio.h>
extern int plus(int x, int y);
//#include "Header.h" //会有错误,因为C语言不支持 extern "C" 错误为:header.h(2): error C2059: syntax error : 'string'
int main()
{
int x=plus(2,3);
printf("%d",x);
getchar();
return 0;
}
C++中引用C语言的函数
//Header1.h
#ifndef C_HEADER_H
extern int plus(int x,int y);
#endif C_HEADER_H
//test.c
#include "Header1.h"
int plus(int x, int y)
{
return x + y;
}
//test2.cpp
#include <stdio.h>
extern "C"{
#include "Header.h"
}
//extern "C" int plus(int,int); 经过测试上面两种extern "C" 方式都可以
int main()
{
int x= plus(2,3);
printf("%d",x);
getchar();
return 0;
}
参考 http://www.cnblogs.com/rollenholt/archive/2012/03/20/2409046.html
C++
551

被折叠的 条评论
为什么被折叠?



