The
source command works fine for pulling a couple of auxiliary Tcl script files into a main Tcl application, or for loading Tcl libraries from a common shared area in small workgroups. But for more extensive collections or for wider distribution, you should consider instead putting together your library as a Tcl
package.
The quick and dirty on creating a Tcl package is as follows:
[ol][li]Collect all the files implementing your package in a single directory.[/li]
[li]In
each file, add a
package provide command that "advertises" that the file provides (a piece of) a particular version of a particular package. For example:
[tt]package provide wonderlib 1.0[/tt][/li]
[li]Start an interactive
tclsh or
wish session.[/li]
[li]Execute the command
pkg_mkIndex, providing it the directory in which your library files reside and, optionally, a glob pattern of the files you want indexed (the default is to index all files in the directory with the extension "[tt].tcl[/tt]"

. For example:
[tt]pkg_mkIndex /usr/local/share/tcl/wonderlib[/tt]
This creates a file in that directory named
pkgIndex.tcl, which is used by Tcl to determine what commands are provided by a package and what it needs to do to load in the package. (You can also create this file by hand, for more complex situations.)[/li][/ol]
Your package is now ready. To use it in an application, you either have to tell Tcl where your package is located, or copy your package (the contents of the library directory) to a place where Tcl automatically looks for packages.
To explicitly tell Tcl where your package is loacted, you need to append the library directory to the special global Tcl variable
auto_path before you attempt to use the library in that application. For example:
Code:
lappend auto_path /usr/local/share/tcl/wonderlib
If instead you copy the library to where Tcl looks for packages automatically, you won't need the line above. The best place to put packages you create is as a subdirectory of the
lib subdirectory of your Tcl installation. In other words, if you've got Tcl installed in
$INSTALL, you could create a subdirectory like
$INSTALL/lib/wonderlib, and then copy all of your Tcl library files (including the
pkgIndex.tcl file) into that directory.
Now, to actually load the package into an application, all you need to do is:
[tt]package require wonderlib[/tt]
It might sound like a lot of steps, but it's actually quite easy to do. Once you've done your first one, you could practically do it in your sleep.
For more information about creating packages, check out the Tcl'ers Wiki (
I'd recommend starting with "package,"
You might also want to check out "A simple package,"
As well as "pkg_mkIndex pitfalls,"
Also, Will Duquette has an excellent document on using Tcl namespaces with packages at
- Ken Jones, President, ken@avia-training.com
Avia Training and Consulting,
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax