Creating two separate executables from a makefile (g++)

后端 未结 2 1645
广开言路
广开言路 2021-02-05 12:50

Currently, I have my makefile set up to compile and make a fairly large project. I have written a second cpp file with main function for running tests. I want these to run sep

2条回答
  •  没有蜡笔的小新
    2021-02-05 13:16

    Normally you would just have multiple targets and do something like this:

    .PHONY: all target tests
    
    all: target tests
    
    target: ...
        ...
    
    tests: ...
        ...
    

    Then you can just make (defaults to make all), or just make target or make tests as needed.

    So for your makefile example above you might want to have something like this:

    CC = g++
    CFLAGS = -c -Wall -DDEBUG -g
    LDFLAGS =
    COMMON_SOURCES = Foo.cpp Bar.cpp A.cpp B.cpp C.cpp
    TARGET_SOURCES = main.cpp
    TEST_SOURCES = test_main.cpp
    COMMON_OBJECTS = $(COMMON_SOURCES:.cpp=.o)
    TARGET_OBJECTS = $(TARGET_SOURCES:.cpp=.o)
    TEST_OBJECTS = $(TEST_SOURCES:.cpp=.o)
    EXECUTABLE = myprogram
    TEST_EXECUTABLE = mytestprogram
    
    .PHONY: all target tests
    
    all: target tests
    
    target: $(EXECUTABLE)
    
    tests: $(TEST_EXECUTABLE)
    
    $(EXECUTABLE): $(COMMON_OBJECTS) $(TARGET_OBJECTS)
        $(CC) $(LDFLAGS) $^ -o $@
    
    $(TEST_EXECUTABLE): $(COMMON_OBJECTS) $(TEST_OBJECTS)
        $(CC) $(LDFLAGS) $^ -o $@
    
    .cpp.o:
        $(CC) $(CFLAGS) $< -o $@
    

提交回复
热议问题