1
votes

I'm trying to build project. There are two directories:

A/
   foo.c
   foo.h
B/
   main.c
   Makefile

main.c includes "foo.h". What do i have to write in Makefile to build the project. I did this

INCLUDE_DIR=../A
LIBS=-lm
CC = gcc
CFLAGS = -c -Wall -I$(INCLUDE_DIR)

default:
    @make clean
    @make main
sample: main.o foo.o
    $(CC) $(LIBS) $? -o $@
main.o: main.c
    $(CC) $(CFLAGS) $< -c $%
foo.o: foo.c
    $(CC) $(CFLAGS) $< -c $%

clean: 
    @rm -rf *.o

It cant find foo.c

2
What version of Make, and where do you want to put foo.o? - Beta

2 Answers

2
votes
INCLUDE_DIR=../A
LIBS=-lm
CC = gcc
CFLAGS = -c -Wall -I$(INCLUDE_DIR)

default:
    @make clean
    @make main
sample: main.o $(INCLUDE_DIR)/foo.o
    $(CC) $(LIBS) $? -o $@
main.o: main.c
    $(CC) $(CFLAGS) $< -c $%
$(INCLUDE_DIR)/foo.o: $(INCLUDE_DIR)/foo.c
    $(CC) $(CFLAGS) $< -c $%

clean: 
    @rm -rf *.o $(INCLUDE_DIR)/*.o

You need to tell make the relative path to the files.

1
votes

IIRC you can use

foo.o: ../A/foo.c
    $(CC) $(CFLAGS) $< -c $%

but I guess that's not really a solution?