20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Communication Between Modules<br />

337<br />

variable moveNumber not just as a global variable, but also as an external global variable.To<br />

reference the value of an external global variable from another module, you must declare<br />

the variable to be accessed, preced<strong>in</strong>g the declaration with the keyword extern,as<br />

follows:<br />

extern <strong>in</strong>t moveNumber;<br />

The value of moveNumber can now be accessed and modified by the module <strong>in</strong> which<br />

the preced<strong>in</strong>g declaration appears. Other modules can also access the value of<br />

moveNumber by <strong>in</strong>corporat<strong>in</strong>g a similar extern declaration <strong>in</strong> the file.<br />

You must obey an important rule when work<strong>in</strong>g with external variables.The variable<br />

has to be def<strong>in</strong>ed <strong>in</strong> some place among your source files.This is done <strong>in</strong> one of two ways.<br />

The first way is to declare the variable outside of any function, not preceded by the keyword<br />

extern, as follows:<br />

<strong>in</strong>t moveNumber;<br />

Here, an <strong>in</strong>itial value can be optionally assigned to the variable, as was shown previously.<br />

The second way to def<strong>in</strong>e an external variable is to declare the variable outside of any<br />

function, plac<strong>in</strong>g the keyword extern <strong>in</strong> front of the declaration, and explicitly assign<strong>in</strong>g<br />

an <strong>in</strong>itial value to it, as follows:<br />

extern <strong>in</strong>t moveNumber = 0;<br />

Note that these two ways are mutually exclusive.<br />

When deal<strong>in</strong>g with external variables, the keyword extern can only be omitted <strong>in</strong><br />

one spot throughout your source files. If you don’t omit the keyword <strong>in</strong> any one spot, <strong>in</strong><br />

exactly one place, you must assign the variable an <strong>in</strong>itial value.<br />

Take a look at a small program example to illustrate the use of external variables.<br />

Suppose you type the follow<strong>in</strong>g code <strong>in</strong>to a file called ma<strong>in</strong>.c:<br />

#<strong>in</strong>clude <br />

<strong>in</strong>t i = 5;<br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

pr<strong>in</strong>tf ("%i ", i);<br />

foo ();<br />

pr<strong>in</strong>tf ("%i\n", i);<br />

}<br />

return 0;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!