static and extern global variables in C and C++

前端 未结 2 542
[愿得一人]
[愿得一人] 2020-11-27 13:57

I made 2 projects, the first one in C and the second one in C++, both work with same behavior.

C project:

header.h

int varGl         


        
相关标签:
2条回答
  • 2020-11-27 14:18

    When you #include a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal variable is defined in the source so it will work no matter how it's declared.

    Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.

    0 讨论(0)
  • 2020-11-27 14:27

    Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

    Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

    What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

    const int varGlobal = 7;
    

    And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

    If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

    Header included by multiple files:

    extern int varGlobal;
    

    In one of your source files:

    int varGlobal = 7;
    
    0 讨论(0)
提交回复
热议问题