Makefile to convert all * .c to * .o

I am writing a Makefile to compile all * .c files into a directory in * .o. There are many * .c files, so I don’t want to do this on an individual basis,

I tried

%.o: %.c
        $(CC) -c $(CFLAGS) $(CPPFLAGS) -o $@ $<

but it doesn’t work ... please help me understand what is going wrong here ...

+4
source share
3 answers

You said makehow to generate *.ofrom the corresponding file *.c. (Not what you need, because you makealready know as much, at least until you try something more specific than what you wrote in your rule.)

, - foo.o bar.o, make .

, Makefile, make foo.o .

----

, , ... , , . , .

, GNU , , patsubst, find GCC ( -MMD -MP). , -, ​​ CMake,

+2

OBJS,

OBJS = $(SRCS:.c=.o)

.c SRCS, :

SRCS = $(wildcard *.c)

, make

$(NAME) : $(OBJS)
          [...]
+1

Your rule maps one file .cto one .oand reflects the existing implicit rule .

To generate all the files .ocorresponding to a set of files .c, you can create a list of object file names from a list of files .c, and then create a target that depends on this list:

SRC = $(wildcard *.c)               # list of source files
OBJS = $(patsubst %.c, %.o, $(SRC)) # list of object files
objs : $(OBJS)                      # target

Then create the object files with

make objs

This will create a file .ofor everyone .c.

+1
source

All Articles