# Unix GNU makefile for Optimizer examples
# Will build all C library examples if no target is specified
#
# The following variables control behavior and must be set (for example
# on the command line or as an environment variable)
#   XPRESSDIR  The root of the Xpress installation
#   OSTYPE     The type of operating system (linux, solaris, aix)
#              If not given explicitly, it will default to the output
#              of the `uname` shell command.
#
# Usage: make [target]
#  [target] can be one of
#    NAME         Builds the specified binary. For example, to compile and
#                 link the knapsack.c program say "make knapsack". This will
#                 produce an executable file called "knapsack".
#    all          Builds all binaries
#    NAME.run     Builds the specified binary and runs it. For example
#                     make knapsack.run
#    all.run      Builds and runs all binaries.
#    clean        Removes all generated files

# Default value for $(OSTYPE) is what the `uname` shell command reports.
OSTYPE = $(shell uname | tr '[A-Z]' '[a-z]')

ifeq ($(OSTYPE),)
$(error Variable OSTYPE not set or empty)
else
$(info OSTYPE=$(OSTYPE))
endif

# Directories in which object and executables files are stored.
OBJDIR = .
EXEDIR = .

# All the files that we can build
FILES = $(addprefix $(EXEDIR)/,$(patsubst %.c,%,$(wildcard *.c)))
ifeq ($(FILES),)
$(error No files found)
endif

# Disable suffix rules
.SUFFIXES:

.PHONY: all clean all.run

all: $(FILES)

# Set XPRESSDIR to the root of your xpressmp installation
INCLUDEPATH=$(XPRESSDIR)/include
LIBRARYPATH=$(XPRESSDIR)/lib

LDFLAGS-linux       = -Wl,-rpath-link="$(LIBRARYPATH)"
LDFLAGS-linux-gnu   = $(LDFLAGS-linux)
LDFLAGS-darwin      = -Wl,-rpath,"$(LIBRARYPATH)"
LDFLAGS=$(LDFLAGS-$(OSTYPE)) $(EXTRA_LDFLAGS)

LDPATH-linux        = LD_LIBRARY_PATH
LDPATH-linux-gnu    = LD_LIBRARY_PATH
LDPATH-darwin       = DYLD_LIBRARY_PATH

LIBS-linux            = -lxprs -lm
LIBS-linux-static     = -lxprs-static -lxprl -lm -lpthread -ldl
LIBS-linux-gnu = $(LIBS-linux)
LIBS-linux-gnu-static = $(LIBS-linux-static)
LIBS-darwin           = -lxprs -lm
LIBS=$(LIBS-$(OSTYPE))
LIBS_STATIC=$(LIBS-$(OSTYPE)-static)

$(OBJDIR)/%.o: %.c
	 $(CC) -Wall -Werror $(CFLAGS) -I"$(INCLUDEPATH)" -c -o $@ $<

$(EXEDIR)/%: $(OBJDIR)/%.o
	$(CC) -L"$(LIBRARYPATH)" -o $@ $< $(LIBS) $(LDFLAGS)

# On some platforms Xpress provides a static library as well and can thus
# create binaries that are linked statically.
ifneq ($(LIBS_STATIC),)
$(EXEDIR)/%-static: %.o
	$(CC) -L"$(LIBRARYPATH)" -o $@ $< $(LIBS_STATIC) $(LDFLAGS)
endif

%.run: $(EXEDIR)/%
	$(LDPATH-$(OSTYPE))=$$$(LDPATH-$(OSTYPE)):$(XPRESSDIR)/lib $(EXEDIR)/$<

all.run: $(addsuffix .run,$(notdir $(FILES)))

clean:
	rm -f $(OBJDIR)/*.o
	rm -f *-static
	rm -f $(FILES)