Search code examples
cexternalpublicextern

Declaration and definition confusion in C


This answer confused me.

If we have two lines in same .c file:

extern int c;
int c;
  • How is the first line of code a declaration and second a definition?
  • Aren't both declarations?
  • How these two lines differ?

Solution

  • The extern keyword is what makes the first line a declaration. It say "this variable exists somewhere". A line like that can appear in a header file.

    The second line is a definition because the extern keyword is not present. If you were to have this line in a header file, two source files that include that header will both define that variable and linking those two files will result in a variable redefinition error.