未定义的符号是一个实现清洁剂检查的功能。如果你看一下生成的代码:
没有消毒:
_Z3foof: # @_Z3foof
.cfi_startproc
# BB#0:
xorps %xmm1, %xmm1
divss %xmm1, %xmm0
ret
带消毒:
_Z3foof: # @_Z3foof
.cfi_startproc
.long 1413876459 # 0x54460aeb
.quad _ZTIFffE
# BB#0:
pushq %rax
.Ltmp1:
.cfi_def_cfa_offset 16
movss %xmm0, 4(%rsp) # 4-byte Spill
movd %xmm0, %esi
movl $__unnamed_1, %edi
xorl %edx, %edx
callq __ubsan_handle_divrem_overflow
xorps %xmm1, %xmm1
movss 4(%rsp), %xmm0 # 4-byte Reload
divss %xmm1, %xmm0
popq %rax
ret
你看它添加的代码做使用该功能的检查。
编译器应在适当的消毒库自动链接,然后我下面的完整的程序:
float foo(float f) { return (f/0); }
int main() {
foo(1.0f);
}
可生产执行时的输出如下:我建
main.cpp:1:32: runtime error: division by zero
,并使用跑指令clang++ -fsanitize=undefined main.cpp && ./a.out
如果您希望编译时检查您希望启用更多编译器警告或静态分析器。但是,似乎没有任何警告或静态分析检查浮点除零错误。
下面是产生一个分析报告的程序:
#include <malloc.h>
int main() {
int *i = (int*) malloc(sizeof(int));
}
与clang++ -std=c++11 main.cpp
编译它不产生任何诊断,但clang++ -std=c++11 --analyze main.cpp
编译它报告如下:
main.cpp:4:10: warning: Value stored to 'i' during its initialization is never read
int *i = (int*) malloc(sizeof(int));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:5:1: warning: Potential leak of memory pointed to by 'i'
}
^
死者店也可以用-Weverything [-Wunused-value]检测到,但泄漏只能由分析仪检测到。
默认全分析结果写入plist文件。你也可以用下面的命令运行分析:
clang++ --analyze -Xanalyzer -analyzer-output=text main.cpp
clang++ --analyze -Xanalyzer -analyzer-output=html -o html-dir main.cpp
要获得的检测问题进行了详细穿行在标准输出或通过分别的注释的源代码的HTML显示,而不是在plist中。
分析仪检查列表here。
请注意,要使分析仪最好地工作,需要分析整个程序,这意味着它需要连接到构建系统。通常的界面是通过IDE(Xcode)或者带有make的scan-build
工具。 CMake有一些铿锵声的功能,比如产生叮声号JSON compilation database files,但如果CMake内置了对铛分析器的内置支持,我不确定。
您应该将您的程序链接到可执行文件并运行它。消毒剂是运行时间的工具。 – osgx
@osgx有趣的是,在我发现没有人编译过的文档中,运行带有'main'函数的东西......所以我开始意识到这是编译时工具。 – user2485710
user2485710,哪些文档?铿锵的手册说:http://clang.llvm.org/docs/UsersManual.html“控制代码生成... -fsanitize = ...打开**运行时检查**各种形式的未定义或可疑的行为...如果检查失败,在运行时会产生一个诊断消息来解释问题。“ – osgx