Previous: Internal File Ops, Up: Extension Example [Contents][Index]
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 steps112 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 extensions (see section How gawk Finds 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["devbsize"] = 512 -| data["mtime"] = 1412004710 -| data["mode"] = 33204 -| data["type"] = file -| data["dev"] = 2053 -| data["gid"] = 1000 -| data["ino"] = 10358899 -| data["ctime"] = 1412004710 -| data["blocks"] = 8 -| data["nlink"] = 1 -| data["name"] = testff.awk -| data["atime"] = 1412004716 -| data["pmode"] = -rw-rw-r-- -| data["size"] = 666 -| data["uid"] = 1000 -| testff.awk modified: 09 29 2014 18:31:50 -| -| Info for JUNK -| ret = -1 -| JUNK modified: 01 01 1970 02:00:00
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 section The gawkextlib Project for Internet links to
the tools.