作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想让编译器在每次在语句之后有声明时抛出一个错误,因为这是我想要强制执行的编码风格,但我也想用 -std=c99 进行编译,因为我使用了一些特定的 c99 功能。
问题是在 c99 中,声明可以在代码中的任何地方使用,而不仅仅是在块的开头。
看看下面的程序:
// prog.c
#include <stdio.h>
int main(void)
{
printf("hello world\n");
int i = 0;
return 0;
}
如果我用
编译此代码gcc 像这样:
gcc -std=c99 -Werror=declaration-after-statement prog.c
它引发以下错误:
prog.c: In function ‘main’:
prog.c:6:9: error: ISO C90 forbids mixed declarations and code [-Werror=declaration-after-statement]
6 | int i = 0;
| ^~~
cc1: some warnings being treated as errors
这是我在使用
编译时想要的行为叮当 ,但是
叮当行为不同。
clang -std=c99 -Werror=declaration-after-statement prog.c
它不会引发任何错误。
clang -std=c90 -Werror=declaration-after-statement prog.c
prog.c:6:6: error: ISO C90 forbids mixing declarations and code [-Werror,-Wdeclaration-after-statement]
int i = 0;
^
1 error generated.
但这对我不利,因为我需要使用
-std=c99
.
-Werror=declaration-after-statement
连同
-std=c99
使用
编译时叮当 ?
最佳答案
查看 clang 的源代码似乎不受支持。
诊断在 clang/include/clang/Basic/DiagnosticSemaKind.td
中定义
def ext_mixed_decls_code : Extension<
"ISO C90 forbids mixing declarations and code">,
InGroup<DiagGroup<"declaration-after-statement">>;
它的唯一用法是在
clang/lib/Sema/SemaStmt.cpp
StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr) {
const unsigned NumElts = Elts.size();
// If we're in C89 mode, check that we don't have any decls after stmts. If
// so, emit an extension diagnostic.
if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
// Note that __extension__ can be around a decl.
unsigned i = 0;
// Skip over all declarations.
for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
/*empty*/;
// We found the end of the list or a statement. Scan for another declstmt.
for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
/*empty*/;
if (i != NumElts) {
Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
Diag(D->getLocation(), diag::ext_mixed_decls_code); // <-- here
}
}
...
请注意
!getLangOpts().C99
在
if
.诊断代码永远不会以高于
c90
的标准执行.
if
的那部分。所以最终得到
if (!getLangOpts().CPlusPlus)
.
cmake -G "Ninja" -DCMAKE_BUILD_TYPE="Release" -DLLVM_ENABLE_PROJECTS="clang" -DLLVM_TARGETS_TO_BUILD="X86" -DCMAKE_C_COMPILER="/usr/bin/gcc" -DCMAKE_CXX_COMPILER="/usr/bin/g++" -DLLVM_PARALLEL_LINK_JOBS=2 -DLLVM_OPTIMIZED_TABLEGEN=ON path/to/llvm-project/llvm
配置 clang 构建
关于c - 如何在 clang 中使用 -std=c99 强制 Werror=declaration-after-statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69270600/
我是一名优秀的程序员,十分优秀!