0

I want to put all the .o file in a different directory.
He can create all the .o file but he can create the .exe file
My Makefile:

CC = gcc
SRC = $(wildcard *.c)
OBJ = $(SRC:.c=.o)
EXEC = exe
CFLAGS = -Wall -pedantic -std=c11 -g


all : $(EXEC)
%.o : %.c
    $(CC) -o prog/$@ -c $< $(CFLAGS)
$(EXEC) : $(OBJ)
    $(CC) -o $@ prog/$^ $(CFLAGS)

clean : rm -rf *.o
mrproper : clean rm -rf $(EXEC) 

And there is the result in shell (Ubuntu):

gcc -o prog/a.o -c a.c -Wall -pedantic -std=c11 -g
gcc -o prog/b.o -c b.c -Wall -pedantic -std=c11 -g
gcc -o prog/main.o -c main.c -Wall -pedantic -std=c11 -g
gcc -o exe prog/a.o b.o main.o -Wall -pedantic -std=c11 -g
gcc: error: b.o: No file or directory
gcc: error: main.o: No file or directory
Makefile:13: recipe for target 'exe' failed
make: * [exe] Error 1

PS : a.c : print A , b.c : print B et main.c use a.c and b.c

melpomene
  • 84,125
  • 8
  • 85
  • 148
Masimisa
  • 3
  • 1
  • 1
    answered here: https://stackoverflow.com/questions/5178125/how-to-place-object-files-in-separate-subdirectory – Dale Dec 09 '18 at 23:59
  • Have you considered using CMake to generate your Makefile rather than building it the hard way? – Dougie Dec 10 '18 at 00:07

1 Answers1

2

I see two issues:

  1. Your %.o rule doesn't actually create %.o files.
  2. prog/$^ expands to prog/a.o b.o main.o because $(OBJ) is a.o b.o main.o.

I'd do it like this:

Instead of OBJ = $(SRC:.c=.o), write

OBJ = $(SRC:%.c=prog/%.o)

The rule for object files then becomes

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

and the executable can be created with

$(EXEC) : $(OBJ)
        $(CC) -o $@ $^ $(CFLAGS)

Finally, for sanity reasons your cleanup rules should probably be

clean :
        rm -rf prog/*.o
mrproper : clean
        rm -rf $(EXEC) 
melpomene
  • 84,125
  • 8
  • 85
  • 148