How do I use extern to share variables between sou

2018-12-30 22:41发布

I know that global variables in C sometimes have the extern keyword. What is an extern variable? What is the declaration like? What is its scope?

This is related to sharing variables across source files, but how does that work precisely? Where do I use extern?

15条回答
后来的你喜欢了谁
2楼-- · 2018-12-30 23:06

extern tells the compiler to trust you that the memory for this variable is declared elsewhere, so it doesnt try to allocate/check memory.

Therefore, you can compile a file that has reference to an extern, but you can not link if that memory is not declared somewhere.

Useful for global variables and libraries, but dangerous because the linker does not type check.

查看更多
忆尘夕之涩
3楼-- · 2018-12-30 23:07

GCC ELF Linux implementation

main.c:

#include <stdio.h>

int not_extern_int = 1;
extern int extern_int;

void main() {
    printf("%d\n", not_extern_int);
    printf("%d\n", extern_int);
}

Compile and decompile:

gcc -c main.c
readelf -s main.o

Output contains:

Num:    Value          Size Type    Bind   Vis      Ndx Name
 9: 0000000000000000     4 OBJECT  GLOBAL DEFAULT    3 not_extern_int
12: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND extern_int

The System V ABI Update ELF spec "Symbol Table" chapter explains:

SHN_UNDEF This section table index means the symbol is undefined. When the link editor combines this object file with another that defines the indicated symbol, this file's references to the symbol will be linked to the actual definition.

which is basically the behavior the C standard gives to extern variables.

From now on, it is the job of the linker to make the final program, but the extern information has already been extracted from the source code into the object file.

Tested on GCC 4.8.

查看更多
看淡一切
4楼-- · 2018-12-30 23:08

extern simply means a variable is defined elsewhere (e.g., in another file).

查看更多
登录 后发表回答