Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add headers to a Makefile?

Tags:

c

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?

like image 748
Robb1 Avatar asked Dec 02 '25 20:12

Robb1


1 Answers

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).

like image 151
Basile Starynkevitch Avatar answered Dec 05 '25 09:12

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!