Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 45.  Compiling Tcl and Extensions

Using Stub Libraries

One problem with extensions is that they get compiled for a particular version of Tcl. As new Tcl releases occur, you find yourself having to recompile extensions. This was necessary for two reasons. First, the Tcl C library tended to changes its APIs from release to release. Changes in its symbol table tie a compiled extension to a specific version of the Tcl library. Another problem occurred if you compiled tclsh statically, and then tried to dynamically load a library. Some systems do not support back linking in this situation, so tclsh would crash. Paul Duffin created a stub library mechanism for Tcl that helps solve these problems.

The main idea is that Tcl creates two binary libraries: the main library (e.g., libtcl8.2.so) and a stub library (e.g., libtclstub.a). All the code is in the main library. The stub library is just a big jump table that contains addresses of functions in the main library. An extension calls Tcl through the jump table. The level of indirection makes the extension immune to changes in the Tcl library. It also handles the back linking problem. If this sounds expensive, it turns out to be equivalent to what the operating system does when you use shared libraries (i.e., dynamic link libraries). Tcl has just implemented dynamic linking in a portable, robust way.

To make your extension use stubs, you have to compile with the correct flags, and you have to add a new call to your extensions Init procedure (e.g., Examplea_Init). The TCL_USE_STUBS compile-time flag turns the Tcl C API calls into macros that use the stub table. The Tcl_InitStubs call ensures that the jump table is initialized, so you must call Tcl_InitStubs as the very first thing in your Init procedure. A typical call looks like this:

if (Tcl_InitStubs(interp, "8.1", 0) == NULL) {
    return TCL_ERROR;

Tcl_InitStubs is similar in spirit to Tcl_PkgRequire in that you request a minimum Tcl version number. Stubs have been supported since Tcl 8.1, and the API will evolve in a backward-compatible way. Unless your extension uses new C APIs introduced in later versions, you should specify the lowest version possible so that it is compatible with more Tcl applications.

      Previous section   Next section