Question:
how to use extern variable in c program?
?
2011-07-20 00:17:34 UTC
how to use extern variable in c program?
Four answers:
peteams
2011-07-20 01:18:09 UTC
extern is used to say a named object, variable or function, exists but is defined elsewhere.



You see extern implicitly being used in the way some people are told to structure source code. Below I've added an explit extern, but the code is the same without it.



extern int Fn();



int main(int argc, char* argv[]) { printf("Function value is %d\n", Fn()); }



int Fn() { return 42; }



You could do the same with a variable:



extern int FourtyTwo;



int main(int argc, char* argv[]) { printf("Variable value is %d\n", FourtyTwo); }



int FourtyTwo = 42;



The extern forward declaration is not restricted to one compilation unit, the extern declaration and actual definition can be in different compiles of different source code. So what you often find is header files that are full of extern declarations of functions and occassionally variables. stdlib.h sometimes defines an extern variable called errno that contains the last error code, although a modern compiler will define it as a macro that calls a function.



It is generally a bad thing to have extern varaiables, they can lead to unexpected and hard to debug behaviour when they're updated wrongly. Mostly you'll find them used for things like an object that represents the one and only running instance of the application.
nieburg
2016-12-30 12:58:30 UTC
C Programming Extern
cazeau
2016-11-11 01:29:56 UTC
C Extern Variable
anonymous
2011-07-20 00:39:07 UTC
Hi there,



You use the extern variable when your source code for C program is contained in two or more text files.



For example:



Your main text file [main.c]



int main()

  {

    extern int your_var;

      your_var = 200;

      print value();

      exit(0);

  }





Your second text file [second.c]



#include



  int your_var;



  void print_value()

    {

      printf("your_var = %d\n", your_var);

    }





In this example, the variable your_var is created in the file second.c, assigned a value in the file main.c, and printed out in the function print_value, which is defined in the file second.c, but called from the file main.c



Hope that simple example helps you understand its purpose and use.



Regards,



Javalad


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...