gpt4 book ai didi

c - 警告 : declaration of 'index' shadows a global declaration

转载 作者:太空狗 更新时间:2023-10-29 17:04:55 25 4
gpt4 key购买 nike

我的编译器 (gcc) 显示警告

warning: declaration of 'index' shadows a global declaration

请帮助我理解为什么会出现此警告。

最佳答案

当你做这样的事情时:

int index;
int main (void) {
int index;
....
return 0;
}

它警告的是 main() 中的 index 实际上 隐藏 你在 之前声明的全局索引主()

它警告您当本地定义处于“事件”状态时您无法获取全局定义。现在这不是必然的问题(因此它只是一个警告),它是完全有效的 C,但您需要了解可能的后果。

As an aside, some C implementations (BSD-based) define an index function in string.h which may also cause a problem. Use of this function is deprecated and it doesn't appear in the C standard (use strchr instead) but it may be the cause of problems if you're running on (for example) Mac OS or OpenBSD (or even Linux under some combination of #define settings, I believe).

有几种方法可以解决这个问题(如果需要的话)。

第一个可能是首选:不要使用全局变量。是的,没错,摆脱他们。他们很少需要,所以不要让我过来打你:-)

我见过的第二种方法是确保它们被“打包”。假设您确实需要全局变量(绝不是确定的,请参阅上一段),创建一个包含它们的结构,如下所示:

myglobs.h:
struct sMyGlobs {
int index;
// all other globals.
};
extern struct sMyGlobs myGlobs;

myglobs.c:
#include "myglobs.h"
struct sMyGlobs myGlobs;

main.c:
#include <stdio.h>
#include "myglobs.h"
int main (void) {
myGlobs.index = 42;
return 0;
}

这样做的好处是很明显,您指的是全局变量并且它们永远不会被隐藏,除非您定义自己的名为 myGlobs 的局部变量。

关于c - 警告 : declaration of 'index' shadows a global declaration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8440973/

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