14.9.2 cdecl

The cdecl modifier can be used to declare a function that uses a C type calling convention. This must be used when accessing functions residing in an object file generated by standard C compilers, but must also be used for Pascal functions that are to be used as callbacks for C libraries.

The cdecl modifier allows to use C function in the code. For external C functions, the object file containing the C implementation of the function or procedure must be linked in. As an example:

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

When compiling this, and linking to the C-library, the strlen function can be called throughout the program. The external directive tells the compiler that the function resides in an external object file or library with the “strlen” name (see 14.7).

Remark The parameters in our declaration of the C function should match exactly the ones in the declaration in C.

For functions that are not external, but which are declared using cdecl, no external linking is needed. These functions have some restrictions, for instance the array of const construct can not be used (due the way this uses the stack). On the other hand, the cdecl modifier allows these functions to be used as callbacks for routines written in C, as the latter expect the “cdecl” calling convention.

Remark In macpas mode, the cdecl modifier can be abbreviated to c.