1

Using make, I need to produce two versions of an executable, which differ by the use of a precompiler flag DXYZ. The way I have this working so far is to produce the *.o objects for the vanilla program, and, another set *.o_xyz for the objects that make use of the -DXYZ flag.

So basically I have two two rules to produce the objects, ie: $(OBJ)/%.o: %.cpp and $(OBJ)/%.o_xyz: %.cpp.

I am wondering if this is this the best way to achieve this? Is it possible to reduce this to a single rule?

CXX=g++

OBJ=./obj
BIN=./bin
INC=-I./inc

CXXFLAGS=-std=c++11 -Wall -Wno-comment
LDFLAGS=-lpthread

CXX_SOURCES=$(wildcard *.cpp)
CXX_OBJECTS=$(patsubst %.cpp, $(OBJ)/%.o,$(notdir $(CXX_SOURCES)))

.PHONY: all
all : program_xyz program
program_xyz: $(addsuffix _xyz,$(CXX_OBJECTS))
    @mkdir -p $(BIN)
    $(CXX) -o $(BIN)/$@ $^ $(LDFLAGS) $(INC) -DXYZ
program: $(CXX_OBJECTS)
    @mkdir -p $(BIN)
    $(CXX) -o $(BIN)/$@ $^ $(LDFLAGS) $(INC)

##Vanilla Endpoints
$(OBJ)/%.o: %.cpp
    @mkdir -p $(@D)
    $(CXX) -c $< -o $@ $(INC) $(CXXFLAGS)

##Endpoint with DXYZ flag
$(OBJ)/%.o_xyz: %.cpp
    @mkdir -p $(@D)
    $(CXX) -c $< -o $@ $(INC) $(CXXFLAGS) -DXYZ
Nicholas Hamilton
  • 10,044
  • 6
  • 57
  • 88
  • 2
    `Is it possible to reduce this to a single rule?` This should never be your priority. Two different pattern rules are okay. `is this the best way to achieve this?` I'd prefer to have two build directories, or maybe to customize base names, as custom extensions look dubious. Also move `mkdir` to order-only prerequisite/rule - it's silly to exec `mkdir` a dozen times in a row. – Matt Apr 18 '19 at 13:50

0 Answers0