-1

How can I make a simple makefile to generate the object files and output binary in a bin directory from any number of c source and header files in a src directory? In this example structure, main includes module_a.h and module_b.h. module_a.h and module_b.h each only include stdio.h.

I can manage the clean rule, but do not know how to automatically generate the .o files and dependencies.

├── bin
├── makefile
├── README.md
└── src
    ├── main.c
    ├── module_a.c
    ├── module_a.h
    ├── module_b.c
    └── module_b.h
tarabyte
  • 17,837
  • 15
  • 76
  • 117
  • possible duplicate of [How do I make a simple makefile? GCC Unix](http://stackoverflow.com/questions/1484817/how-do-i-make-a-simple-makefile-gcc-unix) – Ricky Mutschlechner Jun 04 '15 at 23:23
  • I am so lost @EtanReisner. I thought the original question was poorly asked. You know so many people want this same basic functionality. It is certainly a worthwhile question. – tarabyte Jun 04 '15 at 23:36
  • The makefile in the other question didn't look that bad from my quick look at it. Possibly a bit verbose. The answer in the linked question looks decent at a quick glance also (but has some issues too). The manual is a bit dense but a good read. [The GNU Make Book](http://www.nostarch.com/gnumake) (which I've only read some of) is likely also going to be quite a good resource. – Etan Reisner Jun 04 '15 at 23:39
  • Your second paragraph hints at **automatic dependency detection,** which is an advanced trick. If what you're looking for is a basic makefile, do you know how to write one for when the source files, object files and executables are all in the same directory? – Beta Jun 05 '15 at 00:22

1 Answers1

0

This is a simple Makefile that I use. I'm not a Makefile guru so most likely it can be improved. But it should give you something to start with. The only tricky bit is the dependency handling. I am aware that there are other ways to do this. The example shows one way - generate .d files for each object file which lists the dependencies for that object file. Then include all the .d files into the Makefile to pick up all those dependency rules.

BIN := bin/my_binary

# Include all C files in the src directory
SRCS := $(shell find src -name '*.c')

# List of object files to link
OBJS := $(patsubst %.c,%.o,$(SRCS))

# Link rule
$(BIN): $(OBJS)
    $(CC) -o $@ $(OBJS)

# Include Dependency files
-include $(OBJS:.o=.d)

# Builds object file and generates dependency
%.o: %.c
    $(CC) -c $(CFLAGS) $*.c -o $*.o
    $(CC) -MM $(CFLAGS) $*.c > $*.d
    mv -f $*.d $*.d.tmp
    sed -e 's|.*:|$*.o:|' < $*.d.tmp > $*.d
    rm $*.d.tmp
kaylum
  • 13,833
  • 2
  • 22
  • 31