extern关键字用于声明变量或函数定义在其他文件中,实现跨文件共享。例如file1.cpp定义全局变量int globalValue = 100;file2.cpp通过extern int globalValue声明并使用该变量。

extern 关键字在 C++ 中主要用于声明变量或函数的作用域在其他文件中定义,告诉编译器该符号的定义存在于别的翻译单元(通常是另一个源文件)中,当前只是引用。它的核心作用是**扩展作用域**,实现跨文件的变量和函数共享。
例如:
file1.cpp
int globalValue = 100; // 定义并初始化
file2.cpp
立即学习“C++免费学习笔记(深入)”;
extern int globalValue; // 声明,不分配内存
void printValue() {
std::cout << globalValue << std::endl; // 使用 file1 中定义的变量
}
int globalValue;,会定义一个新的变量,导致链接错误(重复定义)。
例如,在 C++ 中调用 C 编译的函数:
extern "C" {
void c_function(); // 告诉 C++ 编译器使用 C 的链接方式
}
常见写法:
#ifdef __cplusplus
extern "C" {
#endif
void my_c_api_function();
#ifdef __cplusplus
}
#endif
例如共享 const 变量:
// header.h extern const int maxSize; // file1.cpp const int maxSize = 1024;
以上就是c++++中extern关键字的作用_c++ extern关键字的功能与使用场景的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号