P
P
Pinkman2020-05-13 23:36:16
C++ / C#
Pinkman, 2020-05-13 23:36:16

How to save object files in gcc (in a different folder)?

I don’t know how the object files are in a separate folder ... I searched the Internet, found only ways to call Satan from the compiler, but there are no files ... if anything, then the Makefile is like this:

NAME = calc

SRC = main.c \
  parser.c \
  ft_lib/ft_atoi.c \
  ft_lib/ft_putchar.c \
  ft_lib/ft_putnbr.c

OBJ = *.o

FLAGS = #-Wall -Wextra -Werror

all: $(NAME)

$(NAME):
  gcc $(SRC) $(FLAGS) -c
  gcc $(OBJ) -o $(NAME)

clean:
  rm -f $(OBJ)

fclean:
  rm -f $(NAME)

re: fclean all

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-05-13
@famousman204

How to save object files in gcc

Option -o -- path to result, preprocessing/compiling/linking. Teach your Makefile to substitute the correct path for this option.
You say "and I have 100500 source files compiled at once". The answer is, you don't have to. The compiler is still called every time a new one. Write a rule that compiles one file into the correct directory -- and execute it once for each source. For example like this:
NAME = calc

SRC = main.c \
  parser.c \
  ft_lib/ft_atoi.c \
  ft_lib/ft_putchar.c \
  ft_lib/ft_putnbr.c

BUILDDIR=build
OBJ = $(addprefix $(BUILDDIR)/,$(subst /,_,$(patsubst %.c,%.o,$(SRC))))

FLAGS = #-Wall -Wextra -Werror

all: $(NAME)

$(NAME): $(OBJ)
  gcc $(OBJ) -o $(NAME)

define CC_RULE =
$(BUILDDIR)/$(subst /,_,$(patsubst %c,%o,$(SOURCE))): $(SOURCE)
  gcc $(FLAGS) -c $< -o [email protected]
endef

$(foreach SOURCE,$(SRC),$(eval $(call CC_RULE,$(SOURCE))))

clean:
  rm -f $(OBJ)

fclean:
  rm -f $(NAME)

re: fclean all

Look: I made a list of objects from $(SRC), wrote a CC_RULE generator that for any source generates a rule for compiling it into an object under $(BUILDDIR) and called it for all sources in $(SRC).
It's fun, but it's much more practical to use the existing build system: autotools/CMake/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question