Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern with global definition of variable in c

I have the following source code which interests me.

#include <stdio.h>
extern int foo;
int foo = 32;

int main()
{
printf("%d", foo);
}

This a perfectly normal piece of code, and when I compile it with

gcc -Wall -Wextra -pedantic foo.c

I get no warnings.

And it seems weird, because a variable is defined both as external, and also global in the same file. I'm quite sure that it's easy to the linker to find the reference for the external variable in the same file, but doesn't it look like a coding error? And if so, why doesn't the compiler warn about this?

like image 557
stdcall Avatar asked Mar 24 '13 12:03

stdcall


1 Answers

There's nothing weird. You first made a declaration of a variable (you promised the compiler that it exist) and then you actually defined it. There's no problem in that.

Also, by default, all variables that aren't local to functions and aren't defined as static are extern.

like image 60
Alexey Frunze Avatar answered Sep 19 '22 16:09

Alexey Frunze