What's the difference between using extern and #including header files?

前端 未结 2 642
心在旅途
心在旅途 2021-02-01 18:00

I am beginning to question the usefulness of \"extern\" keyword which is used to access variables/functions in other modules(in other files). Aren\'t we doing the same thing whe

相关标签:
2条回答
  • 2021-02-01 18:26

    extern is needed because it declares that the symbol exists and is of a certain type, and does not allocate storage for it.

    If you do:

    int foo;
    

    In a header file that is shared between several source files, you will get a linker error because each source would have its own copy of foo created and the linker will be unable to resolve the symbol.

    Instead, if you have:

    extern int foo;
    

    In the header, it would declare a symbol that is defined elsewhere in each source file.

    One (and only one) source file would contain

    int foo;
    

    which creates a single instance of foo for the linker to resolve.

    0 讨论(0)
  • 2021-02-01 18:32

    No. The #include is a preprocessor command that says "put all of the text from this other file right here". So, all of the functions and variables in the included file are defined in the current file.

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