Why is creating a variable using 'extern' a declaration and not a definition?

后端 未结 5 1284
-上瘾入骨i
-上瘾入骨i 2021-01-21 22:42

I came across the following problem while reading ...just cant get the logic behind this.

auto int c;
static int c;
register int c;
extern int c;
5条回答
  •  耶瑟儿~
    2021-01-21 22:56

    The keyword extern references the fact that the definition of the variable (or possibly function) is elsewhere; the compiler then links this declaration to a defined body in a separate file. The prior three keywords state a declaration - the variable is not defined elsewhere and therefore are not prototypes.

    For instance, say you have a project structure like so:

    ..
    -- main.c
    -- client.c
    -- client.h
    -- server.c
    -- server.h
    

    When gcc compiles these using the header files, the header files typically will define the variables required for the program. This allocates a symbol that links to the declaration of the symbol in the .c files. This is how compilers link up various project files with .o objects. You may be further interested in how this all appears by using objdump -d (assuming you're on Linux) to debug the actual disassembled structure of your program.

    Enjoy and good luck!

提交回复
热议问题