0

I have three directories obj/, inc/ and src/ . The directories inc/ and src/ contains all the .c files. I would like to redirect all the .o files generated in src/ and inc/ to obj/

This is a simple example of my makefile

NAME = push_swap
SRC = $(wildcard ./src/*c)
INC = $(wildcard ./inc/*c)
OBJ1 = $(SRC:.c=.o)
OBJ2 = $(INC:.c=.o)
CC = gcc
CFLAGS = -Wall -Werror -Wextra

$(NAME):    $(OBJ1) $(OBJ2)
    $(CC) $(CFLAGS) $(OBJ1) $(OBJ2) -o $@

all:    $(NAME)

clean:
    rm -f */*.o

fclean: clean
    rm -f $(NAME)

re:     fclean all

The makefile works perfectly, but all the object files are generetad in its src folder, making hard to search for .c files and debbug the code.

Tde-melo
  • 13
  • 2
  • Maybe useful: [Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?](https://stackoverflow.com/q/2908057/1606345) – David Ranieri Jan 07 '23 at 09:16
  • Welcome to Stack Overflow. Would you consider moving all of the source files into `src/`? By convention, `src/` is for source files (`foo.c`), and `inc/` is for header files (`foo.h`). – Beta Jan 07 '23 at 16:44

1 Answers1

0

By default, Make will build the object file in the directory where it finds the source. If you want the object file to be built somewhere else, there is more than one way to do it.

You could write a rule for Make to use instead of the default:

obj/%.o: src/%.c
    $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@

And another for source files in inc/, if you want to keep source files there.

Or you could write a more general rule, and use 'vpath` to find the sources:

vpath %.c src inc

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

EDIT: Did you remember to change the names of the files you ask Make to build (as @MadScientist pointed out in his comment (and as I ought to have pointed out in my Answer))?

Try this:

SRC = $(wildcard ./src/*c)
OBJ1 = $(patsubst ./src/%.c, ./obj/%.o, $(SRC))

CC = gcc
CFLAGS = -Wall -Werror -Wextra

vpath %.c src

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

all: $(OBJ1)
Beta
  • 96,650
  • 16
  • 149
  • 150
  • 1
    However note that in both of these cases, you have to modify how you're creating the `OBJ1` and `OBJ2` variables so they contain the names of the files you actually want to create. Right now they contain `src/foo.o` so that's what make will try to create. – MadScientist Jan 07 '23 at 18:28
  • I can't make it work either way does not work, still to create the object files in the same directory. I can't figure out how to implement it on my Makefile. – Tde-melo Jan 07 '23 at 21:19