c++ - "extern"在函数内部?

标签 c++ c global-variables extern kernighan-and-ritchie

好吧,阅读“有点老”的书(“The C programming language”,第二版,Dennis Ritchie 着),我遇到了以下问题:

An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it

我当时想 - 什么?!

“该变量也必须在每个想要访问它的函数中声明”。然后,我又震惊了一次:

int max; 
/* ... */
int main()
{
    extern int max;
    /* ... */
}

还有一个 - 什么?!


据我所知(显然,这还远远不够),extern 仅在您在某处定义全局变量并且您想通过另一个文件访问它时才有意义(而不是再次定义)。

所以:

  • extern int max inside main 或任何其他函数有什么意义?
  • 标准是否真的说这是一个必须(我需要在每个例子中声明这个max函数,那会用吗?)
  • 这对于 C++ 是否相同(这就是我放置 C++ 标签的原因)?这是我第一次看到这样的东西。

注意:这与 What is the use of declaring a static variable as extern inside a function? 不同。

最佳答案

你的帖子让我吃惊。我不记得了,我很久以前就读过 K&R。我这里只有第一版,它也在那里。然而,这并不是它所说的全部。从第一版开始:

The variable must also be declared in each function that wants to access it; this may be done either by an explicit extern declaration or implicitly by context.

注意“根据上下文隐式”。正文后面:

...if the external definition of a variable occurs in the source file before its use in a particular function, then there is no need for an extern declaration in the function. The extern declarations in main, ... are thus redundant. In fact, common practice is to place definitions of all external variables at the beginning of the source file, and then omit all extern declarations.

也就是说,使 extern 变量可见可以在函数内部完成,也可以在任何函数外部完成,在源文件中跟随它的所有函数。我相信这是本书中唯一在函数内部完成的地方,后来它使用熟悉的一次文件方法。

关于c++ - "extern"在函数内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199656/

相关文章:

c - gsl 无限积分区间错误。发现不良的被积函数行为。如何解决?

c - 如何将结构复制到线程的本地结构中

python - 用 swig 和 python 扩展全局 c 变量数组

c++ - 移走由 std::shared_ptr 管理的对象是否有效

c - 是否可以在 unsigned int 和 unsigned Short 之间进行按位或赋值

c++ - 使用 iomanip 时遇到问题,列未按我预期的方式排列

c - 重新分配字符串数组

jquery - 执行 'if statement' 在控制台中给出奇怪的结果

c++ - 在 C++ 中如何使用模板调用提供类型的特定成员

c++ - 编写构造函数/析构函数是好的做法吗?