Multifile C Programs

CSC 7000-002 Algorithms & Programming
Fall 1999, Mendel 115
Dr. David Matuszek

For various reasons, large programs are split across multiple files. Here is a (small) example.

printarray.c

#include <stdio.h>
void print_array(int a[], int n) {
  int i;
  for (i = 0; i < n; i++)
    printf (" %d", a[i]);
  printf ("\n");
}

printarray.h

void print_array(int a[], int n);

htest.c

#include <stdio.h>
#include "printarray.h"

int main (void) {
  int x[] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
  print_array (x, 6);
}

% gcc -o printtest htest.c printarray.c
% printtest
 1 1 2 3 5 8
%

Keeping track of all the pieces of a large program can get very complicated, so C programmers describe the pieces in a makefile, and use a program called make to compile things as needed.

makefile

printtest: htest.c printarray.c printarray.h
        gcc -o printtest htest.c printarray.c      Note: tab!

% /usr/ccs/bin/make
gcc -o printtest htest.c printarray.c
% printtest
 1 1 2 3 5 8
%