user3575284
user3575284

Reputation: 35

Why size of extern variables is 0 in ELF?

Extern declarations of variables in a c program result in size 0 in ELF. Why isn't actual size stored in ELF when known? For cases like incomplete arrays I understand there is no size information but for other cases it should be possible to store size.

I tried some simple codes and verified in ELF size emitted is zero.

// file1.c

extern int var;
int main()
{
    var = 2;
}
// file 2.c
long long int var = 8;
gcc -c file1.c
readelf -s file1.o
...
9: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND var
...
gcc -c file2.c
readelf -s file2.o
...
7: 0000000000000000     8 OBJECT  GLOBAL DEFAULT    2 var
...

If size of var was stored as 4 in file1.o, linker can actually detect potential mismatch due to size when linking with file2.o.

So why isn't size emitted as it can help catch some subtle issues like this?

Upvotes: 3

Views: 340

Answers (1)

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

In file1, var is just a placeholder. It will not occupy any memory. The extern identifier is to indicate to the compiler and the linker that the variable var is stored elsewhere.

It would be wrong to have two storage locations for the single variable var as you have suggested.

It is a quirk of the C language that you can define a different type for extern variable and a different type for the underlying global variable as you have done in your example. This is one of the reasons that we have static analysis tools.

Upvotes: 6

Related Questions