|
|||
Department of Engineering | |
University of Cambridge > Engineering Department > computing help |
By default, functions and variables defined outside of functions can be accessed from other files, where they should be declared using the extern keyword. If however the variable is defined as static, it can't be accessed from other files. In the following example, `i', `j' and the function `mean' are created in file1.c but only `i' can be accessed from file2.c.
/* file1.c */ int i; static int j; static int mean(int a, int b){ ... |
/* file2.c */ extern int i; |
Names of external variables should be kept short; only the first 6 initial characters are guaranteed to be significant (though in practise the first 255 character often are).
You should keep to a minimum the number of global variables.
You can use include
files to manage your global variables.
#define
s and variable
declarations in it. Make sure all variables are defined as externs.
Include this file in all the relevant source files.
You can achieve this with the help of the pre-processor if your globals.h looks like this:-
#ifdef LOCAL #define EXTERN #else #define EXTERN extern #endif EXTERN int num_of_files; ..
In this way, the `EXTERN' becomes `extern' in every file that includes globals.h. The trick is then to have
#define LOCAL #include "globals.h"in the file containing the main routine.
If you're calling a routine in one file from another file it's all the more important for the formal parameters to be declared correctly. Note especially that the declaration `extern char *x' is not the same as `extern char x[]' - one is of type `pointer-to-char' and the other is `array-of-type-char' (see section 10).