警告:“索引”的声明隐藏了全局声明 [英] warning: declaration of 'index' shadows a global declaration
问题描述
我的编译器(GCC)正显示出警告
My Compiler(gcc) is showing the warning
警告:索引的声明隐藏了全局声明
warning: declaration of 'index' shadows a global declaration
请帮助我了解为什么这个发出警告。
Please help me understand why this warning comes.
推荐答案
当你做的东西像它的:
int index;
int main (void) {
int index;
....
return 0;
}
什么它是警告的是,在首页
在的main()
实际上是隐藏全局的在你面前的main()
。
What it's warning about is that the index
inside main()
is actually hiding the global one you've declared before main()
.
这是警告你,你不能在全局定义,同时获得当地的一个是积极的。现在,这不是的不一定的问题(因此它只是一个警告),这是完全合法的C,但是你需要知道的可能后果。
It's warning you that you can't get at the global definition while the local one is "active". Now that's not necessarily a problem (hence why it's only a warning), it's perfectly valid C, but you need to be aware of the possible consequences.
顺便说一句,一些C实现(基于BSD)定义了一个首页
的功能的 string.h中
其也可造成问题。这个功能的使用pcated德$ P $,它不会在C标准的出现(使用和strchr
代替),但也可能是问题的原因,如果你上运行(例如)的Mac OS或OpenBSD的(下的#define
设置一些组合甚至是Linux的,我相信)。
As an aside, some C implementations (BSD-based) define an
index
function instring.h
which may also cause a problem. Use of this function is deprecated and it doesn't appear in the C standard (usestrchr
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).
有几种方法来解决这个问题(如果需要)。
There are a couple of ways to get around this (if you need to).
首先大概是preferred一:不的使用的全局。是的,这是正确的,摆脱他们。他们很少需要,所以不要让我过来和周围掌掴你: - )
The first is probably the preferred one: don't use globals. Yes, that's right, get rid of them. They're very rarely needed so don't make me come over and slap you around :-)
我见过的第二种方法是,以确保他们打包。假设你实际的需求的全局(绝不是板上钉钉的事情,见previous段),创建一个保存他们的结构,如在以下几点:
A second way I've seen is to ensure they're "packaged". Assuming that you actually need globals (by no means a certainty, see previous paragraph), create a structure that holds them, such as in the following:
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
。
This has the advantage in that it's obvious that you're referring to a global and that they're never hidden, unless you do something like define your own local variable called myGlobs
.
这篇关于警告:“索引”的声明隐藏了全局声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!