Next: , Previous: , Up: Tutorial   [Contents][Index]

4.6 Adding a data file to be installed

Some programs need to access data files when they are run. For example, suppose we print a message from a file, message.


#include <config.h>
#include <stdio.h>
#include <stdlib.h>

#define MESSAGE_FILE "message"

main (void)
  FILE *in;
  char *line = 0;
  size_t n = 0;
  ssize_t result;

  in = fopen (MESSAGE_FILE, "r");
  if (!in)
    exit (1);

  result = getline (&line, &n, in);
  if (result == -1)
    exit (1);

  printf ("%s", line);

Instead of hard-coding the location of the data file, we could define ‘MESSAGE_FILE’ in

AM_CPPFLAGS = -DMESSAGE_FILE=\"$(pkgdatadir)/message\"

AM_CPPFLAGS specifies C preprocessor flags for make to use when building the program. pkgdatadir is a Make variable that is automatically set from the pkgdatadir Autoconf output variable, which in turn is among the several output variables that Autoconf configure scripts always set specifying installation directories. By default, this variable will have the value ‘/usr/local/share/hello’, so the program will look for the data file at ‘/usr/local/share/hello/message’. The user of the program can change this value by giving the --datadir option to configure.

The ‘AM_’ prefix on AM_CPPFLAGS is there to distinguish it from the CPPFLAGS Makefile variable, which may be set by the configure script and/or overridden from the command-line.

We also need the following line in to distribute and install the data file:

dist_pkgdata_DATA = message

The ‘DATA’ part of the variable name corresponds to the kind of object being listed in the variable’s value, in this case data files. The value here is a single file called ‘message’. The ‘pkgdata_’ prefix indicates that the file should be installed in pkgdatadir by ‘make install’, and the ‘dist_’ prefix indicates that the file should be included in the distribution archive created by ‘make dist’.

Next: , Previous: , Up: Tutorial   [Contents][Index]