使用 clang 编译
简单使用 clang 编译
clang 的 选项是 和 gcc 兼容的。所以最简单的用法就是:
clang main.c
在 Makefile 中使用 clang 编译。
使用 $(CC) 或者 $(CXX) 可以通过 环境变量来选择 编译器。
这样可以方便的指定编译器。
- main.c 内容:
用于测试 的 C 程序。
#include <stdio.h>
int main(int argc, char **argv) {
int i;
i = 10;
printf("%d\n", i);
return 0;
}
- Makefile 内容:
注意:
- Makefile 中,不用要 指定 CC 的具体实现。也就是说不要使用包含
CC=gcc,CC:=gcc等的指令。
all:
$(CC) main.c
- 设置 环境变量,指定编译器:
- 不设置
CC。默认使用 cc 也就是 gcc:
# compiling with cc (gcc)
unset CC
unset CXX
make
> cc main.c
- 设置
CC=gcc。使用 gcc:
# compiling with gcc
export CC=gcc
export CXX=g++
make
> gcc main.c
- 设置
CC=clang。使用 clang:
# compiling with clang
export CC=clang
export CXX=clang++
make
> clang main.c
安装 scan-build
scan-build 是用于静态分析代码的工具。
它包含在 clang 的源码包中。
注意:
- scan-build 的版本要和 clang 的一致。
- scan-build 在 git 上有 python 版本。但是不能使用。
# download llvm.x86_64 3.4.2-8.el7 的源码可以通过以下链接下载。
# 但是在这里不是必要的。
# wget http://releases.llvm.org/3.4.2/llvm-3.4.2.src.tar.gz
# dowanload clang-devel.x86_64
# 源码包中包含 scan-build
wget http://releases.llvm.org/3.4.2/cfe-3.4.2.src.tar.gz
# copy scan-build and related to /usr/local/bin
unzip xvf cfe-3.4.2.src.tar.gz
cd cfe-3.4.2.src/tools/scan-build
cp /* /usr/local/bin
使用 scan-build
简单的使用:
只需要 在 make 之前加上 scan-build 就可以了。
scan-build --use-analyzer `which clang` make
注意:
-
scan-build 需要指定 clang 的路径。所以需要设置
--use-analyzer。 -
main.c 内容:
用于测试 的 C 程序。特意少写了返回码。
#include <stdio.h>
int main(int argc, char **argv) {
int i;
i = 10;
printf("%s\n", i);
return ;
}
- 运行 scan-build:
scan-build 发现了 1 个错误:
scan-build --use-analyzer `which clang` make
> scan-build: Using '/usr/bin/clang' for static analysis
> /usr/local/bin/ccc-analyzer main.c
> main.c:9:2: error: non-void function 'main' should return a value [-Wreturn-type]
> return ;
> ^
> 1 error generated.
> scan-build: 0 bugs found.
> scan-build: The analyzer encountered problems on some source files.
> scan-build: Preprocessed versions of these sources were deposited in '/tmp/scan-build-2019-08-17-163932-29084-1/failures'.
> scan-build: Please consider submitting a bug report using these files:
> scan-build: http://clang-analyzer.llvm.org/filing_bugs.html
- 查看错误报告:
具体的错误报告可以在 /tmp/scan-build-2019-08-17-163932-29084-1/failures 查看。它是 html 的。
references:
来源:https://blog.csdn.net/yk_wing4/article/details/99695102