我很好奇链接过程中会发生什么,并且,在我在该领域的研究过程中,我研究了这段代码
#ifdef __cplusplus
extern “C” {
#endif
extern double reciprocal (int i);
#ifdef __cplusplus
}
#endif
代码位于某个头文件中,该头文件被一个程序的.c 和.cpp 源文件包含。它是函数的声明,然后在 .cpp 文件中定义。为什么它有效?我的意思是,在编译 .cpp 文件期间,这将变成
extern "C" {
extern double reciprocal (int i);
}
外部 extern 既使函数在全局范围内可见,又将 C++ 风格的函数名称转换为 C 风格。但也有一个内在的外在。该函数可以外部两次吗?
最佳答案
C++ 语言对添加新关键字过敏,因此有些关键字会被重用以表示不同的含义。 extern
是这些重复使用的关键字之一。它有3 possible meanings :
- 外部链接 - 变量或函数在其他地方定义
- 语言链接 - 变量或函数以“外部”语言定义
- 显式模板实例化声明
在您的情况下,您使用的是 1 和 2。 extern "C"
声明代码具有 "C"
而不是默认的 "C++"
链接。这也意味着外部链接,因此在纯 C++ 代码中您可以编写:
extern "C" {
double reciprocal (int i);
}
和倒数
将自动标记为extern
。添加额外的 extern
没有效果,并且对于没有 extern "C"
包装器的 C 版本是必需的。
请注意,如果您使用 extern "C"
的单一声明版本,则使用第二个 extern
无效:
extern "C" extern double reciprocal (int i);
由于不需要第二个 extern
,因此正确的声明是:
extern "C" double reciprocal (int i);
关于c++ - Extern 在 C++ 中使用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61467251/