使用 extern 指定链接
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++ 支持 string-literal 字段中的字符串 "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;