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 tclConfig.sh 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

 

Usage

bash-2.03$ pwd
/opt/tcl8.4/lib
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
1.0
% calc::add 5 4
9
% calc::sub 7 9
-2
% exit