Previous: Internal File Ops, Up: Sample Library



C.3.2.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 gawk include files, the following steps create a GNU/Linux shared library:

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

Once the library exists, it is loaded by calling the extension built-in function. This function takes two arguments: the name of the library to load and the name of a function to call when the library is first loaded. This function adds the new functions to gawk. It returns the value returned by the initialization function within the shared library:

     # file testff.awk
     BEGIN {
         extension("./filefuncs.so", "dlload")
     
         chdir(".")  # no-op
     
         data[1] = 1 # force `data' to be an array
         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"])
     }

Here are the results of running the program:

     $ gawk -f testff.awk
     -| Info for testff.awk
     -| ret = 0
     -| data["blksize"] = 4096
     -| data["mtime"] = 932361936
     -| data["mode"] = 33188
     -| data["type"] = file
     -| data["dev"] = 2065
     -| data["gid"] = 10
     -| data["ino"] = 878597
     -| data["ctime"] = 971431797
     -| data["blocks"] = 2
     -| data["nlink"] = 1
     -| data["name"] = testff.awk
     -| data["atime"] = 971608519
     -| data["pmode"] = -rw-r--r--
     -| data["size"] = 607
     -| data["uid"] = 2076
     -| testff.awk modified: 07 19 99 08:25:36