简体   繁体   中英

Extern variable declaration and definition

I understand that extern variable is just declaration to inform the compiler that there exists a variable and it can be defined anywhere. My question is can both declaration and definition be present on same file?

main.c

extern int var;
int var = 10;

When you include a header that file is actually copied into your source file (after preprocessing). This means that this is basically always being done if the extern declaration is in a header file included by the source.

You can do this, but there's no point, since the declaration of the variable serves the same purpose. The extern should be placed into a header file and included into this .c file so that the compiler can check that the type you are telling the rest of the program matches the actual type of the variable. You would include the header in other .c files that want to reference the variable. Note that it is not strictly necessary for the .c file that declares the variable to see the extern , but it is a best practice to make sure that the types are consistent.

I remember some code where someone declared a variable:

char error_ message[1024];

In one .c file, and then did:

extern char *error_message;

In another .c file. This compiled and linked just fine, but crashed when the variable was accessed. If the extern had been visible at the declaration, the compiler would have complained about the type mismatch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM