warning: declaration of 'index' shadows a global declaration

前端 未结 1 737
执念已碎
执念已碎 2021-01-12 13:22

My Compiler(gcc) is showing the warning

warning: declaration of \'index\' shadows a global declaration

Please help me understand

相关标签:
1条回答
  • 2021-01-12 13:59

    It's when you do something like:

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

    What it's warning about is that the index inside main() is actually hiding the global one you've declared before main().

    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.

    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).

    There are a couple of ways to get around this (if you need to).

    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 :-)

    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;
        }
    

    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.

    0 讨论(0)
提交回复
热议问题