Compiling and Linking C Extensions in PLT Scheme

Chill out, don’t worry, because we’re going to break it down in a way that won’t put you to sleep (hopefully).

First things first: what the ***** is a dynamic extension? Well, it’s basically a fancy term for a shared library (a.k.a. DLL) that extends PLT Scheme using the C API. And why would you want to do this? Because sometimes you need more power than just plain ol’ Scheme can provide. Maybe you have some complex algorithms or data structures that are better suited for C, and you don’t want to sacrifice performance by implementing them in Scheme.

So how do we go about creating one of these magical extensions? Well, first you write your C code (without declaring anything static, because who needs that kind of negativity in their life?) and provide an appropriate header file for it. Then you compile the C code using the host system’s C compiler with flags to locate PLT Scheme’s header files and generate a shared library.

Next comes linking this is where things get interesting (or at least, more confusing). You run the host system’s C linker with flags to locate and link to PLT Scheme’s libraries, which will generate another shared library that can be loaded by your extension module. If you want to load your extension implicitly through require or load/use-compiled instead of explicitly loading it via load-extension, then you need to write an mzc mode (which is basically a fancy term for a script that helps with building extensions) in one of three modes: cc, ld, or xform.

The cc mode runs the host system’s C compiler and automatically supplies flags to locate PLT Scheme’s header files and compile for inclusion in a shared library. The ld mode runs the host system’s C linker and automatically supplies flags to locate and link to PLT Scheme’s libraries, generating another shared library that can be loaded by your extension module. And finally, the xform mode transforms C code written without explicit GC-cooperation hooks into cooperating with PLT Scheme’s 3m garbage collector (which is a fancy term for memory management).

It may not be the most exciting topic, but it’s an essential part of extending your programming capabilities beyond what plain ol’ Scheme can provide. And who knows? Maybe one day you’ll create a dynamic extension that will change the world (or at least, make your life easier).

SICORPS