14.7 External functions

The external modifier can be used to declare a function that resides in an external object file. It allows to use the function in some code, and at linking time, the object file containing the implementation of the function or procedure must be linked in.

_________________________________________________________________________________________________________
External directive

--external directive-external-----------------------------------------
                          string constant  --     -            -|
                                       -innadmeex- sintrtineggerc coonsntstaantnt-|
___________________________________________________________________

It replaces, in effect, the function or procedure code block. As an example:

program CmodDemo;  
{$Linklib c}  
Const P : PChar = ’This is fun !’;  
Function strlen (P : PChar) : Longint; cdecl; external;  
begin  
  WriteLn (’Length of (’,p,’) : ’,strlen(p))  
end.

Remark The parameters in the declaration of the external function should match exactly the ones in the declaration in the object file.

If the external modifier is followed by a string constant:

external ’lname’;

Then this tells the compiler that the function resides in library “lname”. The compiler will then automatically link this library to the program.

The name that the function has in the library can also be specified:

external ’lname’ name ’Fname’;

This tells the compiler that the function resides in library “lname”, but with name “Fname”. The compiler will then automatically link this library to the program, and use the correct name for the function. Under Windows and os/2, the following form can also be used:

external ’lname’ Index Ind;

This tells the compiler that the function resides in library “lname”, but with index Ind. The compiler will then automatically link this library to the program, and use the correct index for the function.

Finally, the external directive can be used to specify the external name of the function:

external name ’Fname’;  
{$L myfunc.o}

This tells the compiler that the function has the name “Fname”. The correct library or object file (in this case myfunc.o) must still be linked, ensuring that the function “Fname” is indeed included in the linking stage.