7.1.2 Declaring external variables

Some libraries or code blocks have variables which they export. You can access these variables much in the same way as external functions. To access an external variable, you declare it as follows:

Var  
  MyVar : MyType; external name 'varname';

The effect of this declaration is twofold:

  1. No space is allocated for this variable.
  2. The name of the variable used in the assembler code is varname. This is a case sensitive name, so you must be careful.

The variable will be accessible with its declared name, i.e. MyVar in this case.

A second possibility is the declaration:

Var  
  varname : MyType; cvar; external;

The effect of this declaration is twofold as in the previous case:

  1. The external modifier ensures that no space is allocated for this variable.
  2. The cvar modifier tells the compiler that the name of the variable used in the assembler code is exactly as specified in the declaration, but is subject to C name mangling (it can e.g. be prefixed with a _ on some platforms): this means the name is a case sensitive name, so you must be careful.

The first possibility allows you to change the name of the external variable for internal use.

As an example, let’s look at the following C file (in extvar.c):

/*  
Declare a variable, allocate storage  
*/  
int extvar = 12;

And the following program (in extdemo.pp):

Program ExtDemo;  
 
{$L extvar.o}  
 
Var  
  { Case sensitive declaration }  
  extvar : longint; cvar;external;  
  I : longint; external name 'extvar';  
 
begin  
  { Extvar can be used case insensitively }  
  Writeln ('Variable ''extvar'' has value: ',ExtVar);  
  Writeln ('Variable ''I''      has value: ',i);  
end.

Compiling the C file, and the pascal program:

gcc -c -o extvar.o extvar.c  
ppc386 -Sv extdemo

Will produce a program extdemo which will print

Variable 'extvar' has value: 12  
Variable 'I'      has value: 12

on your screen.