I found two contradicting answers how to handle common includes(one, two), so I decided to describe my case...
I have a small project, which originally contains 4 small apps. Assume that I have files A.c, B.c, C.c and D.c. To improve the state of code, I decided to separate common source code. I created Common.h and Common.c. Each app now is dependent on Common.o. Please check below makefile:
OBJ := $(OBJDIR)/A.o $(OBJDIR)/B.o $(OBJDIR)/C.o $(OBJDIR)/D.o
HEADERS := $(SRCDIR)/common.h
MODULES := $(BUILDDIR)/A $(BUILDDIR)/B $(BUILDDIR)/C $(BUILDDIR)/D
all: dir $(OBJ) $(MODULES)
dir :
mkdir -p $(BUILDDIR)
$(BUILDDIR)/A : $(OBJDIR)/A.o $(OBJDIR)/common.o
$(CC) $^ -o $@ $(CFLAGS)
$(BUILDDIR)/B : $(OBJDIR)/B.o $(OBJDIR)/common.o
$(CC) $^ -o $@ $(CFLAGS)
$(BUILDDIR)/C : $(OBJDIR)/C.o $(OBJDIR)/common.o
$(CC) $^ -o $@ $(CFLAGS)
$(BUILDDIR)/D : $(OBJDIR)/D.o $(OBJDIR)/common.o
$(CC) $^ -o $@ $(CFLAGS)
$(OBJDIR)/%.o : $(SRCDIR)/%.c $(HEADERS)
$(CC) -c $< -o $@ $(CFLAGS)
.PHONY: clean
clean:
rm -rf $(BUILDDIR)
In each file *.c I had includes: #include<stdio.h>, #include <stdlib.h>, #include <string.h>
Should I keep these includes in each .c file separately? or is it good practice to put it in common.h?
It seems to me that I can keep these headers in common.h, due to the fact that each application depends on common.o. Is it a proper approach? stdlib.h, stdio.h and string.h are needed in A.c, B.c, C.c, D.c and Common.c (declarations of Common.h do not require any of these files), but putting them in common.h and not including them in each .c file is logical... is this approach correct?
summary: if in each .c file I have malloc (in common.c too), can I put #include <stdlib.h>
only in common.h and then include common.h in all .c files?