Create a simple TCL Package

Please find a simple way to create a tcl package:

We will take create simple calculator package named “calc” with two functions “add” and “sub”
So first we will find tcl library. It is generally the folder which has file with other shared object files which are sourced with the tclsh command.
Now we will create a folder named “calc” same as the package name
Inside this folder we will place two files.
First is the calc.tcl. This file will have the namespace calc with the procs add and sub

# Register the package
package provide calc 1.0
package require Tcl 8.4

# Create the namespace
namespace eval ::calc {
# Export commands
namespace export add sub

# Create procedure in the namespace
proc ::calc::add {a b} {
set result [expr $a + $b]
return $result

proc ::calc::sub {a b} {
set result [expr $a – $b]
return $result

The second file will be the pkgIndex.tcl.
This file will have a line with the package ifneeded command pointing to the tcl file with the namespace.
package ifneeded calc 1.0 “[list source [file join $dir calc.tcl]]”

After setting the files we can now check the package. Remeber the folder calc with the above two files should be in the tcl library path, which in my case is in /opt/tcl8.4/lib
Now we can go into the tcl shell using the command /opt/tcl/bin/tclsh
And use the procs like calc::add 5 4



bash-2.03$ pwd
bash-2.03$ cd calc/
bash-2.03$ ls
calc.tcl pkgIndex.tcl
bash-2.03$ /opt/tcl8.4/bin/tclsh
% package require calc 1.0
% calc::add 5 4
% calc::sub 7 9
% exit


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s