15

In my makefile I have an object variable. I need to prepend obj/ to every .o file. How would I do this?

CC=g++ CFLAGS=-C -Wall LDFLAGS=-lsqlite3 -lpthread -ldl SOURCES=main.cpp Database.cpp actionInit.cpp TileSet.cpp Player.cpp OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=mahjong-counter all: bin $(OBJECTS) $(EXECUTABLE) bin: mkdir -p bin %.o: %.cpp $(CC) $(LDFLAGS) $< -c -o $@ $(EXECUTABLE): $(OBJECTS) $(CC) $(LDFLAGS) $(OBJECTS) -o $(EXECUTABLE) clean: rm $(OBJECTS) 
1

2 Answers 2

19

You want CXX, not CC. CC is for C compiler, not the C++ compiler In any case, I believe the following should work:

CXX=g++ CXXFLAGS=-C -Wall LDFLAGS=-lsqlite3 -lpthread -ldl OBJ_DIR = obj BIN_DIR = bin EXECUTABLE=mahjong-counter SOURCES= main.cpp Database.cpp actionInit.cpp TileSet.cpp Player.cpp OBJECTS= $(SOURCES:%.cpp=$(OBJ_DIR)/%.o) all: dirs $(OBJECTS) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) $(CC) $(LDFLAGS) $(OBJECTS) -o $(EXECUTABLE) $(OBJ_DIR)/%.o: %.cpp $(CXX) $(CXXFLAGS) $< -o $@ dirs: mkdir -p $(BIN_DIR) mkdir -p $(OBJ_DIR) .PHONY: dirs all 
Sign up to request clarification or add additional context in comments.

4 Comments

make: *** No rule to make target mainobj/%.o', needed by all'. Stop. It seems to take the /%.o literally.
Did you add the slash after $(OBJ_DIR)? It looks hidden
CC is for the C compiler, whether or not it's gcc is irrelevant.
Sorry, yeah that's what I meant. Edited. +1@Jack
12

You could use more expressive version of substitution you employed when assigning OBJECTS

OBJECTS=$(SOURCES:%.cpp=obj/%.o) 

or use a standard text transformation function

OBJECTS=$(addprefix obj/,$(SOURCES:.cpp=.o)) 

3 Comments

$(addprefix) is a GNU extension.
Does anybody still use a non-GNU make?
@Maxim: People on non-GNU systems (BSD, Solaris, IRIX, AIX, ...)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.