gpt4 book ai didi

c - 如何在 clang 中使用 -std=c99 强制 Werror=declaration-after-statement

转载 作者:行者123 更新时间:2023-12-04 12:53:37 28 4
gpt4 key购买 nike

我想让编译器在每次在语句之后有声明时抛出一个错误,因为这是我想要强制执行的编码风格,但我也想用 -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().C99if .诊断代码永远不会以高于 c90 的标准执行.
好吧,您肯定可以尝试的一件事是自己构建 clang 并删除 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com