Makefile: rule for placing .o in another directory

I have this directory structure:

  • ./src contains. cpp and .h all the files I need.
  • ./bin should contain .o temporarily and .bin forever. In addition, this folder should be deleted when calling make clean .
  • ./ contains a Makefile

This is my current Makefile :

 CFLAGS = -Wall -pedantic -g CC = g++ EXEC = flrfile SRC_DIR = src BIN_DIR = bin OBJ = FixedLengthFieldsRecord.o FixedLengthRecordFile.o main.o all: flrfile ../$(BIN_DIR)/%.o: $(SRC_DIR)%.cpp $(SRC_DIR)%.h $(CC) $(CFLAGS) -c $(SRC_DIR)%.cpp -o $@ $(EXEC): $(OBJ) @mkdir -p bin $(CC) $(CFLAGS) $(BIN_DIR)/$(OBJ) -o $(BIN_DIR)/$(EXEC) .PHONY : clean clean: -rm -rf $(BIN_DIR) 

When I run make , I get this error:

 make: *** No rule to make target `FixedLengthFieldsRecord.o', needed by `flrfile'. Stop. 

Why is this?

PS: Also, how can I make OBJ = FixedLengthFieldsRecord.o FixedLengthRecordFile.o main.o more general? I do not want to write everything .o ...

+4
source share
1 answer

This is because you do not have a rule for something.o , you have a rule for ../bin/something.o .

If you change the OBJ declaration to

 OBJ = ../$(BIN_DIR)/FixedLengthFieldsRecord.o ../$(BIN_DIR)/FixedLengthRecordFile.o ../$(BIN_DIR)/main.o 

It should work.

You can get objects from the source directory using wildcards

 SOURCES := $(wildcard $(SRC_DIR)/*.cpp) OBJ := $(patsubst $(SRC_DIR)/%,%,$(SOURCES)) OBJ := $(patsubst %.cpp,%.o,$(OBJ)) OBJ := $(addprefix ../$(BIN_DIR)/,$(OBJ)) 

What this means is that first it gets a list of cpp files from $(SRC_DIR) , removes the path, then replaces all cpp suffixes for o and finally adds `../$ $(SRC_DIR) /` before each element.

+3
source

All Articles