1

I'd like to write a simple Makefile which creates all *.o, *.so, and binary files in a build directory, possibly build/.

Is there a straightforward way of doing this in a Makefile? I'm on Linux, Ubuntu 14.04.

The linked question puts all *.o artifacts in a build directory, but not the executables themselves. To be clear, I'd like to hit make and have all items compiled and stored in build/.

Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411
  • you can specify a outputfile with `-o` which can also include a directory. – mch Nov 10 '15 at 20:38
  • Is there a way to set that in my Makefile so if I just run `make`, everything works as planned? I just want to set some default somewhere so that all binaries end up there. – Naftuli Kay Nov 10 '15 at 20:40
  • 1
    see [this post](http://stackoverflow.com/questions/13552575/gnu-make-pattern-to-build-output-in-different-directory-than-src) – jayant Nov 10 '15 at 20:53
  • @jayant That doesn't address my problem: I'd like all `*.o` files _and_ the executables placed in a build directory. – Naftuli Kay Nov 10 '15 at 21:05
  • @NaftuliTzviKay maybe I misunderstood. But in that question all his artefacts are stored in `OBJDIR_DEBUG` which happens to be `Debug`, you want to call it `build`. That's why I thought that link would help. Otherwise to answer your question, yes you can use the Makefile to put all you build artefacts in a separate directory. – jayant Nov 10 '15 at 21:09

1 Answers1

0

Assuming you use GNU make, something like:

O     ?= build
OBJS  := $(patsubst %.c,$(O)/%.o,$(wildcard *.c))
SOS   := $(O)/<you know better than me>
EXECS := $(O)/<you know better than me>

all: $(OBJS) $(SOS) $(EXECS)

$(OBJS): $(O)/%.o: %.c
    mkdir -p $(O); \
    $(CC) $(CFLAGS) -c $< -o $@

$(SOS): ...

$(EXECS): ...

should be close to what you want. As I do not know which *.so and executables you want to build and how, I just indicate a possibility for the rule that builds the *.o. It should be easy to adapt to the other targets.

If you type make, the build sub-directory will be created if it does not exist. If you type make O=foo, the foo sub-directory will be created (if it does not exist) and be used instead of build.

$(OBJS): $(O)/%.o: %.c is a static pattern rule. In case it is not clear enough, the GNU make documentation will tell you everything about them.

Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51