Home > database >  creating two outputs with Makefile
creating two outputs with Makefile

Time:11-05

I want to create a makefile which runs program in C once with "CXXFLAGS = -std=c 11 -g -O3 -DTEST -fopenmp" and one time with: "CXXFLAGS = -std=c 11 -g -O3 -fopenmp" at the end outputs two different files like P1-Test and P1. how can I edit this file?

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

CodePudding user response:

My suggestion:

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 "$@" $^

With sample sources:

  • File main.cpp

     extern void foo(); // should be in second.h or something
    
     int main() { foo(); }
    
  • File second.cpp

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

Results in

$ 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

And of course the outputs:

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

Alternative

If your .o files are really .PRECIOUS, you might want to build separate copies. Here I split into release/main.o and test/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)

Which gives:

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
  • Related