Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help
next up previous contents
Next: Make Up: Source File organisation Previous: Preprocesser Facilities   Contents

Multiple Source Files

Modularisation not only makes the source more easy to manage but it speeds up re-compilation: you need only recompile the changed source files. Also, by keeping the I/O components in one file (and perhaps the text to be printed into another) one can more easily convert the software to run on other machines and in other natural languages.

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.

  1. Construct a `globals.h' file with all of your #defines and variable declarations in it. Make sure all variables are defined as externs. Include this file in all the relevant source files.

  2. In the file that contains your main(), you again have all the variable definitions, minus the externs. This is important - if they are all defined extern, the linker will not be able to allocate memory for them.

You can achieve this with the help of the pre-processor if your globals.h looks like this:-

#ifdef LOCAL
#define EXTERN
#define EXTERN extern
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).

next up previous contents
Next: Make Up: Source File organisation Previous: Preprocesser Facilities   Contents
Tim Love 2010-04-27