Sometimes you want to access a variable in one source file from a program in another. Note that I don't fully approve of this, because it means that code written by one person could affect code written by another. However, sometimes it can be the only way you can share data in a large program. The variable must be declared globally in the source file where it "lives". Functions in other files can refer to it by telling the compiler that the variable is external. This is achieved by putting the keyword extern in front of the variable declaration.

For example, suppose I decide to declare two variables in the lcd.c source file which keep track of the cursor position. I can do this as follows:

In the code on the right the cursor co-ordinate variables are declared in lcdlib. If I want to use them in the main function I have to declare them using extern.

When the compiler sees the word extern it says to itself "Aha! The programmer has declared these variables somewhere else. I do not need to create these variables, but I can use them here and sort this out later when I build the final program". Remember that if you fail to declare the variables later the compiler will eventually realize that something is missing and give you an error.

One other nasty is that if the type of the data is not consistent across the files (i.e. lcdlib says they are char and main says they are int) the C compiler will not notice and produce code which will do strange and interesting things, none of which you want to happen...

 

lcdlib.c

char cursor_x, cursor_y ;

main.c

extern char cursor_x, cursor_y ;