gpt4 book ai didi

c++ - 有什么方法可以为函数指针比较生成警告?

转载 作者:IT老高 更新时间:2023-10-28 12:43:56 26 4
gpt4 key购买 nike

我花了很长时间才发现我的代码中存在由 /OPT:ICF 触发的错误:

Because /OPT:ICF can cause the same address to be assigned to different functions or read-only data members (const variables compiled by using /Gy), it can break a program that depends on unique addresses for functions or read-only data members.

(我一直在存储和比较函数指针是否相等,当链接器丢弃相同的函数时会中断。)

现在我需要找到我可能做过这种事情的每个地方。

测试用例当然是微不足道的:

//MSVC: /Gy /link /OPT:ICF
int test1(void) { return 0; }
int test2(void) { return 0; }
int main(void) { return test1 == test2; }

我尝试过 -Wall-Wextra-Weverything-pedantic 等,但是它们都不会产生警告。

是否有任何编译器选项或工具(无论是 Visual C++、GCC、Clang 或其他的一部分)可以分析我的代码并告诉我在哪里比较函数指针,就像上面的代码一样?

最佳答案

Is there any compiler option or tool (whether part of Visual C++, GCC, Clang, or other) that can analyze my code and tell me where I'm comparing function pointers with each other, like in the code above?

我不确定是否存在这样的编译器选项。

但是,有这样的工具。铿锵有力。您可以编写自己的 clang-tidy 检查,如果您关注 this blog,这实际上非常容易。 .具体来说,AST 已经带有一堆匹配器,它们应该可以处理您想要的用例。

这样的事情似乎有效:

binaryOperator(
anyOf(hasOperatorName("=="), hasOperatorName("!=")),
hasLHS(ignoringImpCasts(declRefExpr(hasType(functionType())))),
hasRHS(ignoringImpCasts(declRefExpr(hasType(functionType())))))

哪个标记了 OP 中的示例:

fp.cxx:3:25: note: "root" binds here
int main(void) { return test1 == test2; }
^~~~~~~~~~~~~~

这特别适用于 OP 案例,但实际上您必须更明确地匹配所有其他可能的案例:

const auto AnyFunc = ignoringImpCasts(declRefExpr(hasType(anyOf(
functionType(),
pointsTo(functionType()),
references(functionType())))));

Finder->AddMatcher(binaryOperator(
anyOf(hasOperatorName("=="), hasOperatorName("!=")),
hasLHS(AnyFunc),
hasRHS(AnyFunc)).bind("op"), this);

或类似的效果。

关于c++ - 有什么方法可以为函数指针比较生成警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48494733/

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