An Introduction To Embedded Tk (page 3 of 32)

[Previous Page][Next Page][Table of Contents]

2 An Example: ``Hello, World!''

The ET system is designed to be easy to use. To see this, let's look at the classic ``Hello, World!'' program, coded using ET.

    void main(int argc, char **argv){
      Et_Init(&argc,argv);
      ET( button .b -text {Hello, World!} -command exit; pack .b );
      Et_MainLoop();
    }
If you compile and link these 5 lines, you'll get a stand-alone executable that pops up a ``Hello, World!'' button, and goes away when the button is clicked.

Let's take this program apart to see how it works. The first thing it does is call the Et_Init() procedure. This procedure performs the tedious and confusing work needed to start up the Tcl/Tk interpreter, initialize widget bindings, create the main window ``.'', and so forth. The last line is a call to another procedure Et_MainLoop() that implements the event loop. (If you don't know what an event loop is, don't worry. We'll have more to say about event loops in section 4.) The most interesting part of the example is the middle line, the one that looks like a call to a function named ET(). The ET() function is special. It looks and is used like a regular C function, but takes a Tcl/Tk script as its argument instead of a C expression. Its function is to execute the enclosed Tcl/Tk. In this particular example, the ET() function creates the ``Hello, World!'' button.

Because of the ET() function, we can't give the ``Hello, World!'' source code directly to a C compiler and expect it to work. We have to run it through a preprocessor first. Like this:

    et2c hello.c > hello_.c
The et2c preprocessor converts the ET() function into real, compilable C code. The preprocessor also takes care of some other housekeeping details, like adding prototypes to the top of the file so that we don't have to bother with a #include. After it has been preprocessed, the source code can be compiled like any other C program.
    cc -O -o hello hello_.c et.o -ltk -ltcl -lXll -lm
Notice that you must link the program with ET's et.o library file, and with libraries for Tcl/Tk and X11. (See section 13 for instructions on building applications for Microsoft-Windows or Macintosh.)

And that's all there is too it!

[Next Page][Table of Contents]