Reputation: 519
Lets say my Makefile is located in the same directory as the sources and I want to store object files in obj/ subdirectory and the target executable in bin/ subdirectory.
src/
main.cpp
test.cpp
test.h
/many other *.cpp files and headers/
Makefile
obj/
bin/
The problem with my Makefile is that I cannot get the OBJECTS variable to contain a list of *.o files with the samy names as *.cpp files, but in OBJDIR subdirectory.
Currently it only works if I name all object files one by one.
CXX=g++
CXXFLAGS=-c -Wall
LDFLAGS=
SOURCES=$(wildcard *.cpp) # very convenient wildcard
BINDIR=bin
OBJDIR=obj
OBJECTS=$(OBJDIR)/main.o $(OBJDIR)/test.o # how do I make a wildcard here?
TARGET=$(BINDIR)/my_executable
all: $(SOURCES) $(TARGET)
$(TARGET): $(OBJECTS)
$(CXX) $(LDFLAGS) $(OBJECTS) -o $@
$(OBJECTS): $(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c $< -o $@
clean:
rm -rf $(OBJDIR)/$(OBJECTS) $(BINDIR)/$(TARGET)
Please help Thank you!
Upvotes: 2
Views: 4333
Reputation:
Similar question to yours already exists on this site here:
Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?
either way something like this should solve your problem:
OBJ_FILES := $(addprefix obj/,$(notdir $(CPP_FILES:.cpp=.o)))
Upvotes: 3