Header file and extern keyword

前端 未结 5 2050
青春惊慌失措
青春惊慌失措 2021-01-22 21:06

I am having a lot of issue using extern variable and header files. I have read through sections of books and searched the web for hours but I haven\'t been able to figure out. A

相关标签:
5条回答
  • 2021-01-22 21:15

    gI must be declared above main:

    int gI = 0;
    
    int main(void)
    {
        ...
    }
    

    By doing this gI has file scope and external linkage.

    Perhaps a better place to declare gI would be in sample.c, if there is such a file.

    0 讨论(0)
  • 2021-01-22 21:18

    Move int gI = 0 outside main() so that it is globally available:

    int gI = 0; 
    int main()
      {
          int i;
    
      ....
      } 
    
    0 讨论(0)
  • 2021-01-22 21:21

    You defined gI inside the scope of the main() function, which makes it visible only from there. I suspect what you really wanted is a global gI variable (hence the extern int gI declaration).

    If you want to have AnotherFunc() see it, move int gI = 0 outside, for instance in the same file than the definition of AnotherFunc().

    0 讨论(0)
  • 2021-01-22 21:32

    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;

    check this link. well explained How do I use extern to share variables between source files?

    0 讨论(0)
  • 2021-01-22 21:33

    You need to declare your variables before using them, and define them exactly once.

    This is a declaration:

    extern int gI;
    

    Basically this just says that there is an int named gI that will be defined elsewhere.

    This is a definition:

    int gI;
    

    This actually creates an int named gI. (Technically it is a declaration as well as a definition.)

    At the moment you have an int gI line inside of your main function, but this is just a shadowing definition. It is a local variable whose name happens to be the same as the declared global gI, but it is not the global gI. So you have a problem where you declared a variable (the global gI) and defined it zero times.

    If you were to put int gI in your sample.h file, it would then be included in both of your .c files. This would also be a problem because the rule is to define variables exactly once, and you will have defined it twice (once in each file).

    The solution is to place the extern declaration in the .h file, and the definition in one of your .c files.

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