Question

Here is my makefile that i am using to build a library. It works well. But it always recompiles all the files. I have declared .PHONY. Still the problem is there.

PROGRAM=mylib


[...]
OBJS= dir/file1.o \
          dir/file2.o

SRC= $(addprefix dir/,$(OBJS))

.PHONY: all clean install
all: ${SRC}
    ${CC} --shared -o lib${PROGRAM}.so ${OBJS}

%.o: %.c
    ${CC} -c ${MY_CFLAGS} $*.c ${INCLUDES}

Also if there are any major concerns with my Makefile please comment.

File tree is as follows :

my_lib
├── include
│   ├── file1.h
└── src
    ├── file1.c
    ├── file2.c
Was it helpful?

Solution

Your SRC_FILES contains src/file1.o and src/file2.o and so on. This is most likely not what you want. By doing this and the $*.c in the generic .c to .o rule you're breaking make's file-rule-dependency automatism.

I'd rewrite your Makefile like this:

[..]

all: lib${PROGRAM}.so     # create dependency from all to your .so

lib${PROGRAM}.so: ${OBJECT_FILES}     # create a dep for your .so to all object files
     ${CC} ${SHARED_FLAGS} -o lib${PROGRAM}.so ${OBJECT_FILES}

%.o: %.c  # generic rule to build .o from .c
     $(CC) -c -o $@ $< $(MY_CFLAGS)

${OBJECT_FILES} has to contain src/file1.o if file1.c is located in src/

The generic rule needs the .o in the same directory as the .c-file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top