Gcc - extern with global definition of variable in c

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/15598750/extern-with-global-definition-of-variable-in-c

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils