Search code examples
cmakefile

makefile for multiple source


while learning make file I am trying to write a make file for multiple source directories it seems i am wrong somewhere

Here is my code structure :

directory
├── common
│   └── fun2.c
├── inc
│   └── fun.h
└── src
    ├── fun1.c
    └── main.c

Here is my makefile:

CC= cc 
CFLAGS = -c -Iinc/
SOURCE=fun1.c\
       main.c\
       common\fun2.c
OBJECTS=$(SOURCE:.c=.o)
EXECUTABLE=hello
all: $(EXECUTABLE)
$(EXECUTABLE):$(OBJECTS)
    $(CC) -o $@ $(OBJECTS)
.c.o:
    $(CC) $(CFLAGS) $< 
clean:
    rm -rf *o hello 

I am getting error when running the makefile

Cannot find a rule to create target common\fun2.o from dependencies. can someone point out what is wrong here


Solution

  • Your .c sources are not in directory, rather in directory/src. Hence the fix:

    SOURCE=src/fun1.c src/main.c common/fun2.c
    

    .c.o: rule is unnecessary, GNU make has a similar built-in rule. Alternatively, fix the rule to output into the correct directory:

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

    -c is an option for application CC to produce a .o, should never be in CFLAGS.

    Targets all and clean should be .PHONY, i.e.:

    .PHONY: all clean