Next: , Previous: , Up: FFI  


6 Compiling and Linking

The c-generate procedure takes a library name and an optional preamble. It reads the library.cdecl file and writes two .c files. The preamble is included at the top of both. It typically contains #include C pre-processor directives required by the C library, but could include additional shim code. Here is a short script that generates a shim for the example “Hello, World!” program.

(load-option 'FFI)
(c-generate "prhello" "#include <gtk/gtk.h>")

This script will produce three files:

prhello-shim.c

This file contains the trampoline functions — one for each declared C extern or callback. It includes the mit-scheme.h header file, found in the AUXDIR directory — e.g. /usr/local/lib/mit-scheme-i386/.

prhello-const.c

This file contains a C program that creates prhello-const.scm. It is compiled and linked as normal for programs using the toolkit, and does not depend on the Scheme machine. It does not actually call any toolkit functions. It just collects information from the compiler about the declared C types and constants.

prhello-types.bin

This file is a fasdumped c-includes structure containing all of the types, constants and functions declared in the .cdecl file.

The following Makefile rules describe the process of building and installing a shim for the example “Hello, World!” program.

AUXDIR=/usr/local/lib/mit-scheme-i386

install: build
	install -m 644 prhello-types.bin $(AUXDIR)
	install -m 644 prhello-const.bin $(AUXDIR)
	install -m 644 prhello-shim.so $(AUXDIR)

uninstall:
	rm $(AUXDIR)/prhello-*

clean:
	rm prhello-const* prhello-types* prhello-shim* 

build: prhello-shim.so prhello-types.bin prhello-const.bin

prhello-shim.so: prhello-shim.o
	$(CC) -shared -fPIC -o $@ $^ `pkg-config --libs gtk+-3.0`

prhello-shim.o: prhello-shim.c
	$(CC) -I$(AUXDIR) -Wall -fPIC `pkg-config --cflags gtk+-3.0` -o $@ -c $<

prhello-shim.c prhello-const.c prhello-types.bin: prhello.cdecl
	echo '(generate-shim "prhello" "#include <gtk/gtk.h>")' \
	| mit-scheme --batch-mode

prhello-const.bin: prhello-const.scm
	echo '(sf "prhello-const")' | mit-scheme --batch-mode

prhello-const.scm: prhello-const
	./prhello-const

prhello-const: prhello-const.o
	$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) `pkg-config --libs gtk+-3.0`

prhello-const.o: prhello-const.c
	$(CC) `pkg-config --cflags gtk+-3.0` $(CFLAGS) -o $@ -c $<

The FFI also supports libraries created by GNU automake (libtool). The source distribution includes several simple plugins. Each uses a portable Makefile.am to build and install its shared object.


Next: Hello World, Previous: Callbacks, Up: FFI