外部在C ++中使用两次

问题描述 投票:1回答:1

我对链接过程中发生的事情非常好奇,并且在我对该领域的研究期间,我st了这段代码

#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 extern-c
1个回答
0
投票

c ++语言对添加新的关键字很敏感,因此有些关键字被重用以表示不同的含义。 extern是这些重复使用的关键字之一。它具有3 possible meanings

  1. 外部链接-变量或函数在其他地方定义
  2. 语言链接-变量或函数以“外部”语言定义
  3. 显式模板实例化声明

在您的情况下,您使用的是1和2。extern "C"声明代码具有"C"而不是默认的"C++"链接。这也意味着外部链接,因此在纯C ++代码中,您可以编写:

extern "C" {
    double reciprocal (int i);
}

并且reciprocal将被自动标记为extern。添加额外的extern无效,对于没有extern "C"包装器的C版本,这是必需的。

请注意,如果您使用的是extern "C"的单声明版本,则使用第二个extern无效:

extern "C" extern double reciprocal (int i);

由于不需要第二个extern,因此正确的声明是:

extern "C" double reciprocal (int i);
© www.soinside.com 2019 - 2024. All rights reserved.