Robb1
Robb1

Reputation: 5025

How to add headers to a Makefile?

I have the following Makefile. How to add also some header files that I have in the project folder (e.g. header1.h with its relative header1.c) ?

CC := gcc
CFLAGS := -Wall -Wextra -Wpedantic -O3
CFILES := $(shell ls *.c)
PROGS := $(CFILES:%.c=%)

all: $(PROGS)

.PHONY: all clean
clean:
    rm -f *~ $(PROGS)

Even adding them one by one would be ok (no need to use the wildcard).

I suppose I should edit the following line:

CFILES := $(shell ls *.c)

But how?

Upvotes: 2

Views: 11136

Answers (1)

First, don't use $(shell ls *.c) but better $(wildcard *.c). Please take time to read the documentation of GNU make

Then, you usually don't want headers in Makefile-s, you want dependencies on headers.

For example, if you know that foo.o needs both foo.c and header.h (because you have some #include "header.h" in your foo.c) you would add a dependency like

foo.o: foo.c header.h

in your Makefile... See also this example.

There is some way to automate such dependencies, using GCC options; read about Invoking GCC, notably preprocessor options like -M

(details depend upon your project and coding conventions)

For a simple project of a few dozen of files totalizing a few thousand lines, you should first write your Makefile explicitly, with the dependencies. Later you might automatize that (but in simple projects that is not worth the trouble).

In some cases, a header file *.h or a C file *.c is generated by some utility (e.g. swig, bison, ... or your own script or program). Then you add appropriate specific rules in your Makefile.

You might use make --trace or remake with -x to debug your Makefile.

Look for inspiration into the source code of some existing free software project (e.g. on github).

Upvotes: 4

Related Questions