gpt4 book ai didi

c++ - 使用 Makefile 创建两个输出

转载 作者:行者123 更新时间:2023-12-04 14:46:57 24 4
gpt4 key购买 nike

我想创建一个 makefile,它在 C++ 中运行一次程序,一次使用“CXXFLAGS = -std=c++11 -g -O3 -DTEST -fopenmp”,一次使用:“CXXFLAGS = -std=c++11 -g -O3 -fopenmp"最后输出两个不同的文件,如 P1-Test 和 P1。我该如何编辑这个文件?

CXX = g++
CXXFLAGS = -std=c++11 -g -O3 -fopenmp

ifdef code_coverage
GCOV_FLAG := -DTEST
else
GCOV_FLAG :=
endif

all: P1
@echo The program has been compiled

# implicit rule: create x from x.cpp
.cpp:
$(CXX) $(CXXFLAGS) $? -o $@
$(CXX) $(CXXFLAGS) $(GCOV_FLAG) $? -o $@
.PHONY: clean
clean:
$(RM) -r P1 *.dSYM

最佳答案

我的建议:

CXX = g++
CXXFLAGS = -std=c++11 -g -O3 -fopenmp

all: P1 P1-Test
@echo The program has been compiled

# implicit rule: create x from x.cpp
.cpp:
$(CXX) $(CXXFLAGS) $? -o $@

.PHONY: clean
clean:
$(RM) -r P1 *.dSYM

P1: main.o second.o
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o "$@" $^

P1-Test: CXXFLAGS+=-DTEST
P1-Test: main.o second.o
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o "$@" $^

带有示例源:

  • 文件 main.cpp

     extern void foo(); // should be in second.h or something

    int main() { foo(); }
  • 文件 second.cpp

     #include <cstdio>

    void foo() {
    #ifdef TEST
    puts("TEST defined");
    #else
    puts("TEST not defined");
    #endif
    }

结果

$ make -B
g++ -std=c++11 -g -O3 -fopenmp -o "P1" main.cpp second.cpp
g++ -std=c++11 -g -O3 -fopenmp -DTEST -o "P1-Test" main.cpp second.cpp
The program has been compiled

当然还有输出:

./P1; ./P1-Test 
TEST not defined
TEST defined

备选

如果您的 .o 文件确实是 .PRECIOUS,您可能想要构建单独的拷贝。这里我拆分成release/main.otest/main.o:

CXX = g++
CXXFLAGS = -std=c++11 -g -O3 -fopenmp

all: P1 P1-Test
@echo The program has been compiled

test/%.o: CXXFLAGS+=-DTEST
test/%.o: %.cpp
mkdir -pv $(@D)
$(CXX) $(CXXFLAGS) $? -c -o $@

release/%.o: %.cpp
mkdir -pv $(@D)
$(CXX) $(CXXFLAGS) $? -c -o $@

.PHONY: clean
clean:
$(RM) -rfv P1 P1-Test *.dSYM release/ test/

P1: release/main.o release/second.o
P1-Test: test/main.o test/second.o

P1 P1-Test:
$(CXX) $(CXXFLAGS) -o "$@" $^ $(LDFLAGS)

给出:

mkdir -pv release
g++ -std=c++11 -g -O3 -fopenmp main.cpp -c -o release/main.o
mkdir -pv release
g++ -std=c++11 -g -O3 -fopenmp second.cpp -c -o release/second.o
g++ -std=c++11 -g -O3 -fopenmp -o "P1" release/main.o release/second.o
mkdir -pv test
g++ -std=c++11 -g -O3 -fopenmp -DTEST main.cpp -c -o test/main.o
mkdir -pv test
g++ -std=c++11 -g -O3 -fopenmp -DTEST second.cpp -c -o test/second.o
g++ -std=c++11 -g -O3 -fopenmp -o "P1-Test" test/main.o test/second.o
echo The program has been compiled

关于c++ - 使用 Makefile 创建两个输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69844567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com