gpt4 book ai didi

c - 错误: extern declaration of 'i' follows declaration with no linkage

转载 作者:行者123 更新时间:2023-12-03 07:39:27 25 4
gpt4 key购买 nike

在以下程序中,我认为extern int i;将更改以下i以引用i外部定义的main:

#include <stdio.h>

extern int i=1; // warning: 'i' initialized and declared 'extern'

int main()
{
int i=2;
printf("%d\n", i);
extern int i; // error: extern declaration of 'i' follows declaration with no linkage
printf("%d\n", i);
return 0;
}

什么是“错误:'i'的外部声明跟随没有链接的声明”的原因,其中“没有链接的声明”是指 int i=2;

在删除 int i=2中的 main之后,
  • 错误消失了,
  • 上的警告“警告:'i'已初始化并声明为'extern'”警告也消失了。这是为什么?

  • 谢谢您的解释!

    最佳答案

    一旦在i函数中定义了一个名为main的变量,文件范围内的i将被屏蔽并且无法访问(除非您具有其地址)。

    当您以后添加声明extern int i时,这与在相同作用域内的名为i的局部变量冲突,因为本地人无法进行外部链接。它确实是而不是,但可以访问全局i

    当您删除本地i时,extern int i声明与文件范围内的定义匹配,因此没有错误。至于extern int i=1;上的警告,在我的gcc 4.1.2上并没有消失,因此这取决于编译器。

    关于c - 错误: extern declaration of 'i' follows declaration with no linkage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64839038/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com