To specify where the object is created use -o
window.o : window.cpp window.h
$(CC) $(LIBS) $(INCLUDEPATH) -c window.cpp -o $(OBJ)/$@
Here is what you could do:
specify the directory where you want the object files to go
OBJDIR = objdir
Create a list of object files that need to be compiled, from the list of all .cpp
files by replacing .cpp
with .o
and add the prefix $(OBJDIR)/
to it:
OBJ = $(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
So your $(OBJ) will look like: objdir/window.o objdir/main.o
and so on
Add a target to create the directory if it does not exist:
$(OBJDIR):
mkdir $(OBJDIR)
Make the directory target before you make your main target:
all: $(OBJDIR) myapp
Rule to compile all the .o
object files in $(OBJDIR)
from .cpp
files in the current directory:
$(OBJDIR)/%.o: %.cpp
$(GCC) $(CPPFLAGS) -c $< -o $@
This will result in something like:
g++ -c main.cpp -o objdir/main.o
Your main target is unchanged:
$(TARGET): $(OBJ)
$(GCC) $(LDFLAGS) -o $@ $^
This will look like:
g++ -o myapp objdir/window.o objdir/main.o
For completeness add clean
target to cleanup objects:
clean:
@rm -f $(TARGET) $(wildcard *.o)
@rm -rf $(OBJDIR)
And define .PHONY
targets, e.g. these will be made even if directories or files with the same name exist:
.PHONY: all clean
So it should look like:
OBJDIR = objdir
OBJ = $(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
TARGET = my app
.PHONY: all clean
all: $(OBJDIR) $(TARGET)
$(OBJDIR):
mkdir $(OBJDIR)
$(OBJDIR)/%.o: %.cpp
$(GCC) $(CPPFLAGS) -c $< -o $@
$(TARGET): $(OBJ)
$(GCC) $(LDFLAGS) -o $@ $^
clean:
@rm -f $(TARGET) $(wildcard *.o)
@rm -rf $(OBJDIR)
And if you have files such as main.cpp
and a.cpp
this is what make
would do:
> ls
Makefile a.cpp main.cpp
> make
mkdir objdir
g++ -I. -c a.cpp -o objdir/a.o
g++ -I. -c main.cpp -o objdir/main.o
g++ -o myapp objdir/a.o objdir/main.o
> ls
Makefile a.cpp main.cpp objdir myapp
> make clean
> ls
Makefile a.cpp main.cpp
And if you want to read more details about any of the above have a look at GNU make doc page
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…