2

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?

Robb1
  • 4,587
  • 6
  • 31
  • 60
  • 3
    Possible duplicate of [Makefile include header](https://stackoverflow.com/questions/15440183/makefile-include-header) – Farnabaz Jan 05 '18 at 09:30
  • 1
    .h files are not very useful as a wildcard in a makefile. They're more useful as manual dependencies – Jean-François Fabre Jan 05 '18 at 09:30
  • 3
    Why do you want headers in makefile? – iBug Jan 05 '18 at 09:34
  • @Jean-FrançoisFabre I edited the OP, I don't need to use the wildcard! I just need gcc to get the correct dependencies – Robb1 Jan 05 '18 at 11:01
  • Notice that folders are GUI artefacts. Your system has [directories](https://en.wikipedia.org/wiki/Directory_(computing)) and most of them do not appear as folders in your GUI desktop – Basile Starynkevitch Jan 05 '18 at 11:14
  • 1
    You don't provide headers to `gcc` but instead the location where it will look for headers. This is done with the `-I` command line parameter. So add to your CFLAGS something like this : `-I "path/to/headers"` – Tim Jan 05 '18 at 13:13

1 Answers1

4

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

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547