"Portable" conditionalization of Makefiles

Christian Weisgerber naddy at mips.inka.de
Wed Mar 21 21:05:09 UTC 2018


On 2018-03-21, "Ronald F. Guilmette" <rfg at tristatelogic.com> wrote:

> So anyway, the problem is that on Linux, I have to link in some different
> libraries to make the stuff work.  Specifically, I have to add -lresolv
> to the link command.  But that's a no-go for FreeBSD, whose linker
> will rightly complain about the missing library if it sees that extra
> option.
>
> Obviously, I need to conditionalize some small bits of my Makefile, but
> I need to do that in a way that will cause -neither- GNU Make nor FreeBSD
> make to barf all over everything.

There is no standard syntax for Makefile conditionals and none that
is in common between GNU make and FreeBSD's make.

You can set variables based on the value of other variables in a way
that is similar to conditionals:

------------------->
OPSYS=FreeBSD
LIBRESOLV_Linux=-lresolv
LIBRESOLV_FreeBSD=
LIBRESOLV=$(LIBRESOLV_$(OPSYS))

prog:
	@echo cc -o prog prog.o $(LIBRESOLV)
<-------------------

But you still need people to set at least one variable (here OPSYS)
either by editing the Makefile or overriding the value from the
command line:

$ make OPSYS=Linux


It is possible to recursively call make from within a Makefile, so
you could use a trick like this to call make again with a distinguishing
variable set to, say, the output of uname:

------------------->
LIBRESOLV_Linux=-lresolv
LIBRESOLV_FreeBSD=
LIBRESOLV=$(LIBRESOLV_$(OPSYS))

all:
	$(MAKE) OPSYS=`uname` prog

prog:
	@echo cc -o prog prog.o $(LIBRESOLV)
<-------------------

-- 
Christian "naddy" Weisgerber                          naddy at mips.inka.de


More information about the freebsd-questions mailing list