Home > Back-end >  Simplest C makefile using implicit rules
Simplest C makefile using implicit rules

Time:12-23

I know it is not optimal at all to rely on make's implicit rules but my goal is to understand why they are not working in this case. I want to write the simplest makefile one can write for a C project without having to specify the sources.

I have tried to run make -d but the ouput is too big and verbose to really be helpful.

I have written makefiles for some time and I believe I am familiar with how it works. I am pretty sure I have managed to get implicit rules to work for me both compiling and linking in the past but apparently I am forgetting something.

Here's what I have tried :

SRCS    =   $(wildcard  *.c)
OBJS    =   ${SRCS:.c=.o}

NAME=exe

${NAME}:    ${OBJS} 

clean:
            rm -rf *.o

fclean:     clean
            rm -rf ${NAME}

re:         fclean ${NAME}

.PHONY: clean fclean re

It almost works but it doesn't link.

I am using gnu make version 4.3

CodePudding user response:

Your Makefile doesn't execute the link step because there is only a very simple implicit rule for linking. From the documentation:

Linking a single object file

n is made automatically from n.o by running the C compiler to link the program. The precise recipe used is $(CC) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS).

This rule does the right thing for a simple program with only one source file. It will also do the right thing if there are multiple object files (presumably coming from various other source files), one of which has a name matching that of the executable file. Thus,

x: y.o z.o

In other words, for your Makefile to work, NAME needs to match the basename of one of your object files.

For example, if I have your Makefile and a single source file named hello.c, I can run:

make NAME=hello

And see the result:

cc    -c -o hello.o hello.c
cc   hello.o   -o hello
  • Related