Thursday 6 June 2019

Extern variables and Functions example in C

Save the below code as ext1.c program

#include <stdio.h>
#include "ext2.c"
/* By using 'extern', you are telling the compiler that whatever
follows it will be found (non-static) at link time; don't reserve
anything for it in the current pass since it will be encountered later.
 Functions and variables are treated equally in this regard.*/
extern void fun(void);
extern int a;
int main(void)
{
    fun();
    printf("%d",a);
  return 0;
}


Save the below code as ext2.c program
#include <stdio.h>
int a=10;
void fun(void)
{
      printf("Hello, world!\n");
}


When you compile and run ext1.c , we get the below output

No comments:

Post a Comment