Question

I am trying to apply this and this to set up a makefile to compile a C++ program so that the object files go to a particular directory and that the source files are in their own separate directory. The main folder has three subfolders test (has some cpp files I want to compile), include (has some headers used by tests), and build (empty folder where I want the .o files to go).

This is the make file.

CC = g++
CFLAGS = -g -Wall

INC_DIR1 = include
INC_DIR2 = C:/armadillo-4.200.0/include
INC_DIR = $(INC_DIR1) $(INC_DIR2)
INCLUDES = $(foreach d, $(INC_DIR), -I$d)

BUILD_DIR = build

SRC_DIR = test
SRC = $(wildcard */*.cpp)

OBJS = $(SRC:.cpp=.o)
#OBJS = $(addprefix $(BUILD_DIR)/, $(notdir $(SRC:.cpp=.o)))
#create objects as the build directory plus the non-directory component of
#source

MAIN = armadillo_extra_functions_test

.PHONY: depend clean

all: $(BUILD_DIR) $(MAIN)
    @echo  amradillo_extra_functions_test has been compiled

$(BUILD_DIR):
    mkdir -p $@

%.o: %.cpp
    $(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@
#$(BUILD_DIR)/%.o: %.cpp
#   $(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@
#put .os in build directory instead of test. 

$(MAIN): $(OBJS) 
    $(CC) $(CFLAGS) $(INCLUDES) -o $(MAIN) $(OBJS)

clean:
    $(RM) *.o *~ $(MAIN) $(BUILD_DIR)/*.o $(SRC_DIR)/*.o

depend: $(SRC)
    makedepend $(INCLUDES) $^

The above code compiles successfully and the exe works properly. However, it puts the .cpps in the test folder. The commented code (instead of the code above it) is adapted from the above links to try to put the .o's in the build directory. However, I get the error

make: *** No rule to make target 'build/armadillo_extra_functions_test.o', neede
d by 'armadillo_extra_functions_test'.  Stop.

When I took the .o files from the first version of the code, put them in the build folder, deleted the exe, and ran the commented version, it compiled just fine.

As such, I think the issue is related to the %.o: %.cpp part. The .o files are named something like /build/blah.o and the source files are named something like /test/blah.cpp. I tried a few different combinations, such as the prefix version above with the $(BUILD_DIR)/%.o: %.cpp and without, but no luck.

I don't want to have to rely adding a move command to the make file and would rather get the %.o:%.cpp part working properly.

Was it helpful?

Solution

Setting the intrinsic make variable VPATH should help to find sources for 'out of source tree builds'. Just set it like this:

VPATH = $(SRC_DIR)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top