获取编译器警告的摘要

问题描述 投票:0回答:1

有没有办法在构建结束时获得所有编译器警告的摘要?在Makefile上使用g ++

makefile g++ warnings compiler-warnings
1个回答
1
投票

您可以创建自己的make命令进行编译,并在配方中使用它。例如,您可以自动将编译器的标准和错误输出记录到文本文件中,并将grep全部用于构建结束时的警告。像(使用GNU make)的东西:

# $(1): source file
# $(2): object file
# $(3): log file
MYCXX = $(CXX) $(CXXFLAGS) -c $(1) -o $(2) 2>&1 | tee $(3)

CXXFLAGS += -Wall -pedantic

%.o: %.cpp
    $(call MYCXX,$<,$@,$*.log)

OBJS := $(patsubst %.cpp,%.o,$(wildcard *.cpp))
LOGS := $(patsubst %.o,%.log,$(OBJS))

top: $(OBJS)
    $(CXX) $(LDFLAGS) $^ -o $@
    @printf '\nSummary of warnings\n###################\n\n'
    @for l in $(LOGS); do grep -i -10 warning $$l || true; done

演示:

$ make
g++ -Wall -pedantic -c b.cpp -o b.o 2>&1 | tee b.log
g++ -Wall -pedantic -c c.cpp -o c.o 2>&1 | tee c.log
g++ -Wall -pedantic -c a.cpp -o a.o 2>&1 | tee a.log
g++ -Wall -pedantic -c d.cpp -o d.o 2>&1 | tee d.log
c.cpp: In function ‘int c()’:
c.cpp:1:18: warning: unused variable ‘vc’ [-Wunused-variable]
 int c(void) {int vc; return 0;}
                  ^~
a.cpp: In function ‘int a()’:
a.cpp:1:18: warning: unused variable ‘va’ [-Wunused-variable]
 int a(void) {int va; return 0;}
                  ^~
b.cpp: In function ‘int b()’:
b.cpp:1:18: warning: unused variable ‘vb’ [-Wunused-variable]
 int b(void) {int vb; return 0;}
                  ^~
g++  b.o c.o a.o d.o -o top

Summary of warnings
###################

b.cpp: In function ‘int b()’:
b.cpp:1:18: warning: unused variable ‘vb’ [-Wunused-variable]
 int b(void) {int vb; return 0;}
                  ^~
c.cpp: In function ‘int c()’:
c.cpp:1:18: warning: unused variable ‘vc’ [-Wunused-variable]
 int c(void) {int vc; return 0;}
                  ^~
a.cpp: In function ‘int a()’:
a.cpp:1:18: warning: unused variable ‘va’ [-Wunused-variable]
 int a(void) {int va; return 0;}
                  ^~

甚至还有一种更优雅的方式,包括(重新)定义CXX标准make变量并为其分配一个小的shell脚本来完成工作,这样你就可以像往常一样使用CXX

CXX = function mycxx { g++ $$* 2>&1 | tee $(patsubst %.o,%.log,$@) ;}; mycxx

%.o: %.cpp
    $(CXX) $(CXXFLAGS) -c $< -o $@

当通过make扩展foo.o目标时,配方变为:

function mycxx { g++ $* 2>&1 | tee foo.log ;}; mycxx -Wall -pedantic foo.cpp -o foo.o

shell最终会执行:

g++ -Wall -pedantic foo.cpp -o foo.o 2>&1 | tee foo.log

最终结果应与第一个解决方案相同,但对Makefile的修改要少得多。除了CXX的(重新)定义之外,它应该保持不变(假设你在食谱中使用CXX,这是推荐的)。

© www.soinside.com 2019 - 2024. All rights reserved.