Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change current directory in GNU Make

I want to separate the directory with sources from the directory with targets. And it seems that changing the current working directory from Makefile should be the simplest solution.

Explicit path to targets is not sufficient because of the following drawbacks:

  1. Redundant code in Makefile since every reference to target should be prefixed with variable.
  2. More complex command line to build particular intermediate target (worse for debugging).

See also Pauls's rule #3:

Life is simplest if the targets are built in the current working directory.

Regarding VPATH — I also agree that requiring developers "to change to the target directory before running make is a pain".

like image 237
ruvim Avatar asked May 26 '16 17:05

ruvim


Video Answer


2 Answers

Building targets in a separate directory is a commonplace make practice that GNU make conveniently supports without changing directory or invoking auxiliary tools. Here is a routine illustration:

Makefile

srcs := main.c foo.c
blddir := bld
objs := $(addprefix $(blddir)/,$(srcs:.c=.o))
exe := $(blddir)/prog

.PHONY: all clean

all: $(exe)

$(blddir):
    mkdir -p $@

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

$(exe) : $(objs)
    $(CC) -o $@ $^ $(LDFLAGS) $(LDLIBS)

clean:
    rm -fr $(blddir)

which runs like:

$ make
mkdir -p bld
cc   -c -o bld/main.o main.c
cc   -c -o bld/foo.o foo.c
cc -o bld/prog bld/main.o bld/foo.o

Cribs:-

  • $(addprefix $(blddir)/,$(srcs:.c=.o))
    • 8.2 Functions for String Substitution and Analysis
    • 6.3.1 Substitution References
  • $(blddir)/%.o: %.c | $(blddir)
    • 10.5 Defining and Redefining Pattern Rules
    • 4.3 Types of Prerequisites

There can be powerful reasons to make make change its working directory but merely putting build products in a separate directory isn't one.

like image 107
Mike Kinghan Avatar answered Sep 19 '22 09:09

Mike Kinghan


In the GNU Make program I am using built for mingw64 (windows),

GNU Make 4.2.1 Built for x86_64-w64-mingw32

I am able to use this target with this command,

debug:
    cd $(PREFIX) && $(GDB) kiwigb.exe

The results are the directory change is temporary, but all works.

like image 28
user2262111 Avatar answered Sep 22 '22 09:09

user2262111