Makefile export .o file to a different path than .

2020-02-15 09:08发布

So my task is simple, I have created the makefile (New with makefiles) and I want to keep my .o files in a different folder to have a cleaner directory and allow the usage of .o files by others.

I searched and found many solution pointing to using -o $< $@

However, it is giving me that g++: cannot specify -o with -c or -S with multiple files

This is what I want to do:

$(OBJECT_PATH)/file1.o: $(SOURCE_PATH)/file2.cpp $(SOURCE_PATH)/file1.cpp
        $(CC) $(CFLAGS) $(SOURCE_PATH)/file2.cpp $(SOURCE_PATH)/file1.cpp -o $@

file1.cpp has #include "file1.h", so from what I read I should include file1.cpp in the dependencies. However, now I can't export to a different directory.

Is there a solution? Or do I have the concept wrong?

2条回答
Deceive 欺骗
2楼-- · 2020-02-15 09:27

try

$(OBJECT_PATH)/file1.o: $(SOURCE_PATH)/file2.cpp $(SOURCE_PATH)/file1.cpp
    $(CC) $(CFLAGS) $^ -c $@

and check that CFLAGS doesn't include -o -c or -s flags

also read about implicit rules. it might help you to orginzie your makefile

查看更多
Fickle 薄情
3楼-- · 2020-02-15 09:28

Use make -d or even better remake -x to understand what commands are invoked.

Run also make -p to understand what builtin rules are used.

We cannot help you more, because we have no idea if you redefined CFLAGS.

And C++ compilation should better be done with g++ that is CXX and CXXFLAGS, e.g. with (I am extracting this from my make -p output)

LINK.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) $(TARGET_ARCH)
COMPILE.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
CXX = g++
%.o: %.cc
      $(COMPILE.cc) $(OUTPUT_OPTION) $<

I strongly suggest to have CXXFLAGS= -Wall -g at least during the development phase. Learn also to use gdb and valgrind.

You could have the following in your Makefile

 CXXFLAGS= -g -Wall
 SOURCES=f1.cc f2.cc
 SOURCE_PATH=yoursourcedir/
 OBJECT_PATH=yourobjectdir/
 SRCFILES=$(patsubst %.cc,$(SOURCE_PATH)/%.cc,$(SOURCES))
 OBJFILES=$(patsubst %.cc,$(OBJECT_PATH)/%.o,$(SOURCES))
 PROGFILE=$(OBJECT_PATH)
 .PHONY: all clean
 all: $(PROGFILE)
 $(PROGFILE): $(OBJFILES)
         $(LINK.cc) $^ $(LOADLIBES) $(LDLIBS) -o $@
 $(OBJECT_PATH)/%.o: $(SOURCE_PATH)/%.cc
         $(COMPILE.cc)  $(OUTPUT_OPTION) $<
 clean:
         $(RM) $(OBJECT_PATH)/*.o $(PROGFILE)
查看更多
登录 后发表回答