Next: The Make Utility Up: External variables and functions Previous: External variables and functions

Scope of externals

An external variable (or function) is not always totally global.

C applies the following rule:

The scope of an external variable (or function) begins at its point of declaration and lasts to the end of the file (module) it is declared in.

Consider the following:

main cannot see what_scopeor end_of_scope but the functions what_global and fn can. ONLY fn can see alone.

This is also the one of the reasons why we should prototype functions before the body of code etc. is given.

So here main will not know anything about the functions what_global and fn. what_global does not know about fn but fn knows about what_global since it is declared above.

NOTE: The other reason we prototype functions is that some checking can be done the parameters passed to functions.

If we need to refer to an external variable before it is declared or if it is defined in another module we must declare it as an extern variable. e.g.

extern int what_global

So returning to the modular example. We have a global string AnotherString declared in main.c and shared with WriteMyString.c where it is declared extern.

BEWARE the extern prefix is a declaration NOT a definition. i.e NO STORAGE is set aside in memory for an extern variable - it is just an announcement of the property of a variable.

The actual variable must only be defined once in the whole program - you can have as many extern declarations as needed.

Array sizes must obviously be given with declarations but are not needed with extern declarations. e.g.:

main.c: int arr[100]:

file.c: extern int arr[];


Dave.Marshall@cm.cf.ac.uk
Fri May 20 13:40:49 BST 1994