Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - External variables

Node:External variables, Next:, Previous:Storage classes, Up:Storage classes



External variables

Sometimes the source code for a C program is contained in more than one text file. If this is the case, then it may be necessary to use variables that are defined in another file. You can use a global variable in files other than the one in which it is defined by redeclaring it, prefixed by the extern specifier, in the other files.

File main.c                  File secondary.c

                          #include <stdio.h>
                          int my_var;
int main()
{
  extern int my_var;      void print_value()
                          {
  my_var = 500;             printf("my_var = %d\n", my_var);
  print_value();          }
  exit (0);
}

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

See Compiling multiple files, for information on how to compile a program whose source code is split among multiple files. For this example, you can simply type the command gcc -o testprog main.c secondary.c, and run the program with ./testprog.

 
 
  Published under free license. Design by Interspire