make: Loaded Object Example

1 
1 12.2.4 Example Loaded Object
1 ----------------------------
1 
1 Let's suppose we wanted to write a new GNU 'make' function that would
1 create a temporary file and return its name.  We would like our function
1 to take a prefix as an argument.  First we can write the function in a
1 file 'mk_temp.c':
1 
1      #include <stdlib.h>
1      #include <stdlib.h>
1      #include <stdio.h>
1      #include <string.h>
1      #include <unistd.h>
1      #include <errno.h>
1 
1      #include <gnumake.h>
1 
1      int plugin_is_GPL_compatible;
1 
1      char *
1      gen_tmpfile(const char *nm, int argc, char **argv)
1      {
1        int fd;
1 
1        /* Compute the size of the filename and allocate space for it.  */
1        int len = strlen (argv[0]) + 6 + 1;
1        char *buf = gmk_alloc (len);
1 
1        strcpy (buf, argv[0]);
1        strcat (buf, "XXXXXX");
1 
1        fd = mkstemp(buf);
1        if (fd >= 0)
1          {
1            /* Don't leak the file descriptor.  */
1            close (fd);
1            return buf;
1          }
1 
1        /* Failure.  */
1        fprintf (stderr, "mkstemp(%s) failed: %s\n", buf, strerror (errno));
1        gmk_free (buf);
1        return NULL;
1      }
1 
1      int
1      mk_temp_gmk_setup ()
1      {
1        /* Register the function with make name "mk-temp".  */
1        gmk_add_function ("mk-temp", gen_tmpfile, 1, 1, 1);
1        return 1;
1      }
1 
1    Next, we will write a makefile that can build this shared object,
1 load it, and use it:
1 
1      all:
1              @echo Temporary file: $(mk-temp tmpfile.)
1 
1      load mk_temp.so
1 
1      mk_temp.so: mk_temp.c
1              $(CC) -shared -fPIC -o $ $<
1 
1    On MS-Windows, due to peculiarities of how shared objects are
1 produced, the compiler needs to scan the "import library" produced when
1 building 'make', typically called 'libgnumake-VERSION.dll.a', where
1 VERSION is the version of the load object API. So the recipe to produce
1 a shared object will look on Windows like this (assuming the API version
1 is 1):
1 
1      mk_temp.dll: mk_temp.c
1              $(CC) -shared -o $ $< -lgnumake-1
1 
1    Now when you run 'make' you'll see something like:
1 
1      $ make
1      cc -shared -fPIC -o mk_temp.so mk_temp.c
1      Temporary filename: tmpfile.A7JEwd
1