I have this really weird doubt in extern usage

Consider the code

#include<stdio.h>

int main(void)
{
extern int a;
printf("%d",a);

getch();
return 0;
}
int a=20;

How is it that this code gives the output as 20 ???


My guess
Since its an extern variable, it can be declared anwhere( even outside the main).
Since its the same file, we dont have to do a #include"samefile.h"

Please correct me...

Dani AI

Generated

and gave the right, short explanation. A couple of practical clarifications and pitfalls that are often missed:

The important distinction is declaration vs definition. A plain extern int a; is only a declaration: it tells the compiler "there is an object named a with external linkage" but does not allocate storage. The actual storage is created by a definition such as int a = 20; (or by an extern that also has an initializer). For example:

/* a.c */
extern int a = 20;   /* this is a definition (allocates storage) */

/* main.c */
#include <stdio.h>
extern int a;         /* just a declaration */
int main(void){ printf("%d\n", a); }

Common problems and tips:

  • If there is no definition anywhere, the link step fails with an "undefined reference" / unresolved symbol error.
  • If you accidentally provide two full definitions (e.g., int a = 20; in two .c files), the linker will complain about multiple definitions.
  • Use static at file scope to make a variable private to that translation unit (internal linkage). That prevents other files from seeing it via extern.
  • Initialization order of globals across different translation units is not specified in C, so avoid depending on one global being initialized before another in a different .c file.

Best practice: put extern declarations in a header that multiple .c files include, and put exactly one definition in one .c file. For details on linkage and storage rules see the C language reference on declarations and linkage: Declarations, , Storage duration.

Recommended Answers

All 2 Replies

extern means the variable may be declared in another source file or later in the same source file. See the remarks here

Also, the value of global variables are set before main() is called, which is why printf() can display the correct value of that variable.

Since its the same file, we dont have to do a #include"samefile.h"

Since headers provide declarations, and the extern declaration already does that, including a header at all is unnecessary. You can still have two files:

/* foo.c */
int a = 20;
/* main.c */
#include <stdio.h>

int main(void)
{
    extern int a;

    printf("%d\n", a);

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.