7.1.1 Declaring external functions or procedures

The first step in using external code blocks is declaring the function you want to use. Free Pascal supports Delphi syntax, i.e. you must use the external directive. The external directive replaces, in effect, the code block of the function.

The external directive doesn’t specify a calling convention; it just tells the compiler that the code for a procedure or function resides in an external code block. A calling convention modifier should be declared if the external code blocks does not have the same calling conventions as Free Pascal. For more information on calling conventions section 6.3, page 405.

There exist four variants of the external directive:

  1. A simple external declaration:
    Procedure ProcName (Args : TPRocArgs); external;

    The external directive tells the compiler that the function resides in an external block of code. You can use this together with the {$L} or {$LinkLib} directives to link to a function or procedure in a library or external object file. Object files are looked for in the object search path (set by -Fo) and libraries are searched for in the linker path (set by -Fl).

  2. You can give the external directive a library name as an argument:
    Procedure ProcName (Args : TPRocArgs); external 'Name';

    This tells the compiler that the procedure resides in a library with name ’Name’. This method is equivalent to the following:

    Procedure ProcName (Args : TPRocArgs);external;  
    {$LinkLib 'Name'}

  3. The external can also be used with two arguments:
    Procedure ProcName (Args : TPRocArgs); external 'Name'  
                                           name 'OtherProcName';

    This has the same meaning as the previous declaration, only the compiler will use the name ’OtherProcName’ when linking to the library. This can be used to give different names to procedures and functions in an external library. The name of the routine is case-sensitive and should match exactly the name of the routine in the object file.

    This method is equivalent to the following code:

    Procedure OtherProcName (Args : TProcArgs); external;  
    {$LinkLib 'Name'}  
     
    Procedure ProcName (Args : TPRocArgs);  
     
    begin  
      OtherProcName (Args);  
    end;

  4. Lastly, under Windows and os/2, there is a fourth possibility to specify an external function: In .DLL files, functions also have a unique number (their index). It is possible to refer to these functions using their index:
    Procedure ProcName (Args : TPRocArgs); external 'Name'  
                                           Index SomeIndex;

    This tells the compiler that the procedure ProcName resides in a dynamic link library, with index SomeIndex.

    RemarkNote that this is only available under Windows and os/2.