Tcl HomeTcl Home hosted by
ActiveState

Google SiteSearch

How to Use the Tcl Stubs Library

This page provides a "how to" guide to the stubs library found introduced in Tcl 8.1 and available in all later releases. The main advantage of using the stubs library is that your extension can be linked once against the stubs library, and then be used with later versions of Tcl as well1. Another advantage of stubs is that you can create a statically linked Tcl shell and still be able to dynamically load a stubs-aware extension.

When you build or install Tcl, you will notice a new library, libtclstub8.3.a. This library implements a dynamically bound interface to Tcl. In other words, it provides a level of indirection between the code in a Tcl extension and the Tcl library. The indirection is completed at runtime so your extension is not hardwired to a particular instance of the Tcl library. This is essentially the same thing that happens when you link against a shared library (e.g., a .dll, .so, or .sl file), except that Tcl implements the linking in a portable way.

In order to use the stubs library you need to make the following modifcations to your extension:

  1. Add the -DUSE_TCL_STUBS and -DUSE_TK_STUBS (if Tk is used) flags to your makefile. You need to compile your code with these so that the Tcl API turns into macros that go through the stubs library.
  2. Link against -ltclstub8.3 instead of -ltcl8.3
  3. Include the following code as the first statement in your extension's Init procedure (e.g., Foo_Init)
        if (
    #ifdef USE_TCL_STUBS
    	Tcl_InitStubs(interp, "8.3", 0)
    #else
    	Tcl_PkgRequire(interp, "Tcl", "8.3", 0)
    #endif
    	== NULL) {
    	return TCL_ERROR;
        }
    
    This call validates that the Tcl application that loads your extension can support the stubs interface you require (in this case, version 8.3 or later). You can use TCL_VERSION to guarantee the current version you are building against is the minimum.
1 If you build against 8.3 stubs, your extension will be compatible with versions 8.3 or later, but not 8.2. This assumes only public Tcl C APIs and structures are used. Stubs does not guarantee version independence with private C APIs and structures.