Proper ways to write Makefile for a relatively large C program?

Viewed 70

Program tree:

├── Makefile
├── foo
├── lib
│   └── foo.h
└── src
    └── foo.c

I am wondering if there are proper ways to write the Makefile to compile a C program like this structure? Like putting all .c files inside src folder whilst keeping all header files in lib folder.

Tried to write Makefile for it but it did not work as expected... And also, I was trying to make .o files in build folder but I'm not sure how to do that. If I have many files from both src and lib folder, what's the proper way to link them together?

My Makefile:

CC := gcc
CFLAGS := -std=c99 -Werror -Wall
TARGET := foo
LIBDIR := lib
SRCDIR := src
BUILDDIR := build
LIBS = -Ilib
.PHONY: all
.PHONY: clean

all: ${TARGET}

$(TARGET): $(TARGET).c,$(wildcard $(LIBDIR)/ *.h)
    ${CC} ${CFLAGS} ${LIBS} ${SRCDIR}/${TARGET}.c

clean:
    rm -rf $(TARGET)

Showing up errors when I do make

make: *** No rule to make target 'foo.c,lib/foo.h', needed by 'foo'.  Stop.
2 Answers

To fix the issue, you need to replace the comma with a space in $(TARGET): what,ever

The best way to make these applications would be to add instructions on compiling for each object or library you introduce

Such as adding files.o

files.o: files.c files.h
   // Compile command

Thanks for the useful advice! I ended up with writing the part like this:

%.o: ${LIBDIR}/%.h
    mkdir ${BUILDDIR}
    ${CC} ${CFLAGS} -c ${LIBDIR}/${TARGET}.h -o ${BUILDDIR}/${TARGET}.o
$(TARGET): $(TARGET).o 
    ${CC} ${CFLAGS} ${LIBS} ${SRCDIR}/${TARGET}.c -o $(TARGET)
Related