next up previous contents
Next: Linking to a library Up: Linking issues Previous: Using external variables

Linking to an object file

 

Having declared the external function or variable that resides in an object file, you can use it as if it was defined in your own program or unit. To produce an executable, you must still link the object file in. This can be done with the {$L file.o} directive.

This will cause the linker to link in the object file file.o. On LINUX systems, this filename is case sensitive. Under DOS, case isn't important. Note that file.o must be in the current directory if you don't specify a path. The linker will not search for file.o if it isn't found.

You cannot specify libraries in this way, it is for object files only.

Here we present an example. Consider that you have some assembly routine that calculates the nth Fibonacci number :

.text
	.align 4
.globl Fibonacci
	.type Fibonacci,@function
Fibonacci:
	pushl %ebp
	movl %esp,%ebp
	movl 8(%ebp),%edx
	xorl %ecx,%ecx
	xorl %eax,%eax
	movl $1,%ebx
	incl %edx
loop:
	decl %edx
	je endloop
	movl %ecx,%eax
	addl %ebx,%eax
	movl %ebx,%ecx
	movl %eax,%ebx
	jmp loop
endloop:
	movl %ebp,%esp
        popl %ebp
	ret
Then you can call this function with the following Pascal Program:
Program FibonacciDemo;

var i : longint;

Function Fibonacci (L : longint):longint;cdecl;external;

{$L fib.o}

begin
  For I:=1 to 40 do
    writeln ('Fib(',i,') : ',Fibonacci (i));
end.
With just two commands, this can be made into a program :
as -o fib.o fib.s
ppc386 fibo.pp
This example supposes that you have your assembler routine in fib.s, and your Pascal program in fibo.pp.



Michael Van Canneyt
Thu Sep 10 14:04:11 CEST 1998