[Solved] Breaking up large C program in Header files and C files


Your headers will contain the type definitions and function declarations for the relevant sections of code. Note that if the user code (primarily main.c) only calls mergesort() and not merge(), then the mergesort.h header should only declare mergesort() and merge() should be a static function in mergesort.c, hidden from the rest of the code. A header should only define what ‘clients’ need to know; implementation details should be kept hidden. Remember to ensure that the headers are self-contained (so if mergesort.h needs to know about struct node, it includes the header that declares struct node, for example). Also ensure they are idempotent (so writing #include "header.h" twice won’t cause compilation errors). This is done with header guards such as:

#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED

…body of header file…

#endif /* HEADER_H_INCLUDED */

The source files will contain the implementations of the functions declared in the headers. The source files will include the relevant headers. Parts of the code that don’t need to know about a given structure type shouldn’t need to include the header that declares that structure type.

The outline makefile can be simple:

FILES.c = main.c student.c mergesort.c aux.c
FILES.o = ${FILES.c:.c=.o}

all: students

students: ${FILES.o}
    ${CC} ${CFLAGS} -o $@ ${FILES.o} ${LDFLAGS} ${LDLIBS}

students.o:  students.h
mergesort.o: mergesort.h
aux.o:       aux.h

Since make knows how to build xyz.o from xyz.c, you don’t need to specify those dependencies. You should declare the headers used by main.c (so you need a line such as main.o: students.h mergesort.h aux.h, but you’ve not indicated what’s correct).

2

solved Breaking up large C program in Header files and C files