How to write a single makefile, c files are in src

2019-04-12 13:59发布

问题:

I am trying to write a makefile which should pick the sources from src/ and headers from inc/

~/Linuz/src: 1.c, 2.c, 3.c ...

~/Linuz/inc: abc.h, dyz.h

Please help me to create a makefile which should be available at

~/Linuz/some_other_dir/Makefile

PS: Trying to compile it for my linux machine.

Thank you for your suggestions.

回答1:

all: my_program

%.o: ../src/%.c
    $(CC) $(CFLAGS) -I../inc/ -c -o $@ $^

my_program: 1.o 2.o 3.o 
    $(CC) $(LDFLAGS) -o $@ $^

clean:
    rm -f *.o my_program

If you put your Makefile in the ~/Linuz/some_other_dir/, the following rule

%.o: ../src/%.c

will get the c files from the ../src/ folder (~/Linuz/src/) and create the object (*.o) files in the same folder of the Makefile.

The -I../inc/ option means that the makefile canl get a header files from the ../inc/ folder (~/Linuz/inc/).

The my_program: 1.o 2.o 3.o rule means that the makefile will create the binary in the same directory of Makefile from the object files 1.o and 2.o and 3.o

From the make manual:

$^ The names of all the prerequisites, with spaces between them. For prerequisites which are archive members, only the member named is used (see Archives). A target has only one prerequisite on each other file it depends on, no matter how many times each file is listed as a prerequisite. So if you list a prerequisite more than once for a target, the value of $^ contains just one copy of the name. This list does not contain any of the order-only prerequisites; for those see the `$|' variable, below.

$@ The file name of the target of the rule. If the target is an archive member, then ‘$@’ is the name of the archive file. In a pattern rule that has multiple targets (see Introduction to Pattern Rules), ‘$@’ is the name of whichever target caused the rule's recipe to be run.