2017-06-08 55 views
1

我的文件夾結構如下所示:如何調整Makefile以使測試成爲目標?

src 
--main.cpp 
tests 
--src 
----main_test.cpp 
Makefile 

我想打一個目標像make main_test,爲了能夠運行測試程序爲./main_test

最初我有一個Makefile,我很久沒修改過了。所以我開始修改它的內容,以創建新的main_test目標。

的Makefile

CXX = g++ 
CXXFLAGS = -O2 -Wall -std=c++11 -Iinclude 
LDFLAGS = 

EXE = main 
SRCDIR = src 
BINDIR = bin 
OBJDIR = tests/bin 

OBJECTS = $(patsubst $(SRCDIR)/%.cpp,$(BINDIR)/%.o,$(wildcard 
$(SRCDIR)/*.cpp)) 

all: $(EXE) 

$(EXE): $(BINDIR) $(OBJECTS) 
    $(CXX) $(OBJECTS) -o $(EXE) $(LDFLAGS) 

$(BINDIR)/%.o: $(SRCDIR)/%.cpp 
    $(CXX) $(CXXFLAGS) -c -MMD -o [email protected] $< 

include $(wildcard $(BINDIR)/*.d) 

$(OBJDIR): 
    mkdir -p $(OBJDIR) 

main_test: $(OBJDIR) tests/bin/main_test.o 
    g++ -O2 -Wall -std=c++11 tests/bin/main_test.o -o tests/main_test 

tests/bin/main_test.o: $(OBJDIR) tests/src/main_test.cpp 
    g++ -O2 -Wall -std=c++11 tests/src/main_test.cpp -o tests/bin/main_test.o 

clean_tests: 
    rm -rf $(OBJDIR) 

$(BINDIR): 
    mkdir -p $(BINDIR) 

clean: 
    rm -rf $(BINDIR) $(EXE) 

.PHONY: clean all 

不幸的是,出現了一些問題:

make main_test 
mkdir -p tests/bin 
g++ -O2 -Wall -std=c++11 tests/src/main_test.cpp -o tests/bin/main_test.o 
g++ -O2 -Wall -std=c++11 tests/bin/main_test.o -o tests/main_test 
tests/bin/main_test.o: In function `_start': 
(.text+0x1f0): multiple definition of `_start' 
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here 
tests/bin/main_test.o: In function `_fini': 
(.fini+0x0): multiple definition of `_fini' 
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here 
tests/bin/main_test.o:(.rodata+0x0): multiple definition of `_IO_stdin_used' 
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here 
tests/bin/main_test.o: In function `data_start': 
(.data+0x0): multiple definition of `__data_start' 
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here 
tests/bin/main_test.o: In function `data_start': 
(.data+0x8): multiple definition of `__dso_handle' 
/usr/lib/gcc/x86_64-linux-gnu/5/crtbegin.o:(.data+0x0): first defined here 
tests/bin/main_test.o: In function `_init': 
(.init+0x0): multiple definition of `_init' 
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here 
/usr/lib/gcc/x86_64-linux-gnu/5/crtend.o:(.tm_clone_table+0x0): multiple definition of `__TMC_END__' 
tests/bin/main_test.o:(.data+0x10): first defined here 
/usr/bin/ld: error in tests/bin/main_test.o(.eh_frame); no .eh_frame_hdr table will be created. 
collect2: error: ld returned 1 exit status 
Makefile:26: recipe for target 'main_test' failed 
make: *** [main_test] Error 1 

我應該如何解決這個問題?

回答

2

tests/bin/main_test.o的編譯規則中,您錯過了-c命令行選項。


使用輸出目錄的order-only dependency,例如:

main_test: tests/bin/main_test.o | $(OBJDIR)