Embedding Tcl in C/C++ Applications

Presented At:
The Tcl2K Conference
Austin, Texas
9:00am, February 15, 2000
  Instructor:
D. Richard Hipp
drh@hwaci.com
http://www.hwaci.com/drh/
704.948.4565

Copies of these notes, example source code,
and other resources related to this tutorial
are available online at http://www.hwaci.com/tcl2k/

$Id: index.html 11708 2007-02-12 23:01:19Z shyouhei $



Tutorial Outline



Embedding Tcl in C/C++ Applications



Why Mix C With Tcl/Tk?



Why Mix C With Tcl/Tk?

"Use C for the things C is good at and use Tcl/Tk for the things Tcl/Tk is good at."

C is good at:
  • Speed
  • Complex data structures
  • Computation
  • Interacting with hardware
  • Byte-by-byte data analysis
  Tcl/Tk is good at:
  • Building a user interface
  • Manipulation of strings
  • Portability
  • Opening sockets
  • Handling events


Programming Models

Mainstream Tcl Programming Model:

 

Embedded Tcl Programming Model:  

  • Add bits of C code to a large Tcl program
 
  • Add bits of Tcl code to a large C program
  • Main Tcl script loads extensions written in C
 
  • Main C procedure invokes the Tcl interpreter
  • Tcl/Tk is a programming language
 
  • Tcl/Tk is a C library

Most of the Tcl2K conference is about
 

This tutorial is about


"Hello, World!" Using The Tcl Library

#include <tcl.h>       Always include <tcl.h>
int main(int argc, char **argv){
  Tcl_Interp *interp;
  interp = Tcl_CreateInterp();       Create a new Tcl interpreter
  Tcl_Eval(interp, "puts {Hello, World!}");       Execute a Tcl command.
  return 0;
}


Compiling "Hello, World!"

Unix:

$ gcc hello.c -ltcl -lm -ldl
$ ./a.out
Hello, World!

Windows using Cygwin:

C:> gcc hello.c -ltcl80 -lm
C:> a.exe
Hello, World!

Windows using Mingw32:

C:> gcc -mno-cygwin hello.c -ltcl82 -lm
Also works with VC++



Where Does -ltcl Come From On Unix?

Build it yourself using these steps:



What Other Libraries Are Required For Unix?



How To Compile Under Unix Without Installing Tcl

Specify the *.a file directly:

  $ gcc -I../tcl8.2.2/generic hello.c \ 
      ../tcl8.2.2/unix/libtcl8.2.a -lm -ldl
  $ strip a.out
  $ ./a.out
  Hello, World!

Or, tell the C compiler where to look for *.a files:

  $ gcc -I../tcl8.2.2/generic hello.c \ 
      -L../tcl8.2.2/unix -ltcl -lm -ldl
  $ strip a.out
  $ ./a.out
  Hello, World!
The -I../tcl8.2.2 argument tells the compiler where to find <tcl.h>.



What's "Cygwin"?