c++ - Extern 在 C++ 中使用了两次

标签 c++ extern extern-c

我很好奇链接过程中会发生什么,并且,在我在该领域的研究过程中,我研究了这段代码

#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. 语言链接 - 变量或函数以“外部”语言定义
  3. 显式模板实例化声明

在您的情况下,您使用的是 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/

相关文章:

c++ - 集成数据库,易于手动维护

c++ - 正确使用 Boost::ref ..?

python - 为 Python 制作外部枚举 "public"?

c++ - 外部 "C"或不外部 "C"[g++ vs cl]

c++ - 从 C++ 链接到 Fortran 库 (Lapack)

c++ - 如何添加钱面额c++

c++ - C++ 中的简单文件 I/O - 从不退出此循环?

rust - 如何使用 Rust 中的 C typedef 结构和该结构的函数?

C++:extern "C"和类成员之间的命名空间冲突

c++ - extern "C"仅在函数声明中需要吗?