confused about the extern keyword

This question already has an answer here:

  • What is the effect of extern “C” in C++? 12 answers
  • When to use extern in C++ 5 answers

  • Obligatory point #1: this relates to global variables, so the first thing you really need/want to do is not learn how to use them, but how to avoid them. They're much more likely to lead to problems than a solution.

    That said, at least in the usual case, you put an extern declaration in a header. You put the definition of the variable in one source file, and you include the header in any other file that needs access to that variable.

    For example:

    //file1.cpp:
    int var;
    

    Then the header that declares the variable:

    //file1.h:
    extern int var;
    

    Then in one file that needs access to the variable:

    #include "file1.h"
    
    int main() {
        var = 10; // Yes, this *is* allowed
    }
    

    ...and in another file that needs access to the variable:

    #include "file1.h"
    
    int f() { return var; }
    

    I'll repeat though: this is almost never necessary or desirable. If you're actually using globals very often at all, you're probably doing something wrong (I make it a practice to use a global once a year so I don't forget how, but it's been at least a few years since I used any other than that).


    Basically the extern keyword tells the compiler/linker that it should expect the variable to be instantiated and defined elsewhere in the program, for example a library you are linking to or whatever object file "somefile.h" compiles to. Extern lets the compielr and programmer "know" about a variable while letting another piece of code actually manage it.

    Here is a good explanation of extern: https://stackoverflow.com/a/496476/1874323


    extern effectively means that somewhere, in all the linked obj files/libraries there exists a variable (in your case) called "var of type int, the compiler doesn't know where, but he'll let the linker find it for you". This keeps the compiler happy.

    In your case, you're right, 'int var=1;' must be defined somewhere, actually, in accpp file, not a header (if it was in a header, you wouldn't need to extern it, you could just #include it).

    If you extern a variable, but don't define it somewhere, the linker will get unhappy - with an unresolved symbol error (ie its saying "you told me to look for a variable called 'var', but I can't find it).

    So - theoretically, you should not be able to create an executable with an extern'd variable which isn't defined.

    链接地址: http://www.djcxy.com/p/40492.html

    上一篇: 在不同的文件中使用相同的变量(使用extern)

    下一篇: 对extern关键字感到困惑