Previous: , Up: Extension Example   [Contents][Index]


16.6.3 Integrating The Extensions

Now that the code is written, it must be possible to add it at runtime to the running gawk interpreter. First, the code must be compiled. Assuming that the functions are in a file named filefuncs.c, and idir is the location of the gawkapi.h header file, the following steps105 create a GNU/Linux shared library:

$ gcc -fPIC -shared -DHAVE_CONFIG_H -c -O -g -Iidir filefuncs.c
$ gcc -o filefuncs.so -shared filefuncs.o

Once the library exists, it is loaded by using the @load keyword.

# file testff.awk
@load "filefuncs"

BEGIN {
    "pwd" | getline curdir  # save current directory
    close("pwd")

    chdir("/tmp")
    system("pwd")   # test it
    chdir(curdir)   # go back

    print "Info for testff.awk"
    ret = stat("testff.awk", data)
    print "ret =", ret
    for (i in data)
        printf "data[\"%s\"] = %s\n", i, data[i]
    print "testff.awk modified:",
        strftime("%m %d %y %H:%M:%S", data["mtime"])

    print "\nInfo for JUNK"
    ret = stat("JUNK", data)
    print "ret =", ret
    for (i in data)
        printf "data[\"%s\"] = %s\n", i, data[i]
    print "JUNK modified:", strftime("%m %d %y %H:%M:%S", data["mtime"])
}

The AWKLIBPATH environment variable tells gawk where to find shared libraries (see Finding Extensions). We set it to the current directory and run the program:

$ AWKLIBPATH=$PWD gawk -f testff.awk
-| /tmp
-| Info for testff.awk
-| ret = 0
-| data["blksize"] = 4096
-| data["mtime"] = 1350838628
-| data["mode"] = 33204
-| data["type"] = file
-| data["dev"] = 2053
-| data["gid"] = 1000
-| data["ino"] = 1719496
-| data["ctime"] = 1350838628
-| data["blocks"] = 8
-| data["nlink"] = 1
-| data["name"] = testff.awk
-| data["atime"] = 1350838632
-| data["pmode"] = -rw-rw-r--
-| data["size"] = 662
-| data["uid"] = 1000
-| testff.awk modified: 10 21 12 18:57:08
-| 
-| Info for JUNK
-| ret = -1
-| JUNK modified: 01 01 70 02:00:00

Footnotes

(105)

In practice, you would probably want to use the GNU Autotools—Automake, Autoconf, Libtool, and Gettext—to configure and build your libraries. Instructions for doing so are beyond the scope of this Web page. See gawkextlib, for WWW links to the tools.