使用外部指定连接
extern string-literal { declaration-list }
extern string-literal declaration
备注
extern 关键字声明变量或函数并指定它有外部链接 (其名称从文件可见而该定义) 内容之外。 当修改变量, extern 中指定该变量具有静态持续时间 (分配,而程序启动时和移除的内存,当程序关闭时)。 变量或函数可以定义在另一个源文件或以后在同一文件。 变量和函数的默认情况下声明在文件范围外部。
示例
// specifying_linkage1.cpp
int i = 1;
void other();
int main() {
// Reference to i, defined above:
extern int i;
}
void other() {
// Address of global i assigned to pointer variable:
static int *external_i = &i;
// i will be redefined; global i no longer visible:
// int i = 16;
}
在 C++ 中,使用时,与字符串, extern 指定其他语言的连接惯例是使用声明。 ,仅当它们以前声明为具有 C 链接, C 函数和数据进行访问。 但是,在一个单独编译翻译单元必须定义它们。
Microsoft C++ 支持在 字符串文本 字段中的字符串 “C” 和 “C++” 。 所有的标准包含文件使用 extern “C”语法允许运行库函数在 C++ 程序。
下面的示例演示的替代方法声明具有 C 链接的名称:
// specifying_linkage2.cpp
// compile with: /c
// Declare printf with C linkage.
extern "C" int printf( const char *fmt, ... );
// Cause everything in the specified header files
// to have C linkage.
extern "C" {
// add your #include statements here
#include <stdio.h>
}
// Declare the two functions ShowChar and GetChar
// with C linkage.
extern "C" {
char ShowChar( char ch );
char GetChar( void );
}
// Define the two functions ShowChar and GetChar
// with C linkage.
extern "C" char ShowChar( char ch ) {
putchar( ch );
return ch;
}
extern "C" char GetChar( void ) {
char ch;
ch = getchar();
return ch;
}
// Declare a global variable, errno, with C linkage.
extern "C" int errno;