如何制作 g++拒绝任何表现出未定义行为的代码?
我想向我的构建系统添加一个 CXXFLAG
,强制整个代码库得到良好定义。因此,每一段以静态方式表现出未定义行为的代码都应该被编译器拒绝。
例如,reinterpret_cast(someIntPtr)->aMember 没有任何未定义的运行时上下文 (a),而 int i = bar(); i /= i; 可能会导致未定义的行为 (b),具体取决于 bar()
的运行时评估(可能返回零)。
我只期望(a)案件能够被抓获,而不一定是(b)案件。
I would like to add a CXXFLAG
to my build systems that force the entire code-base to be well-defined. So every piece of code that exhibits undefined behaviour in a static fashion, should be refused by the compiler.
For instance reinterpret_cast<A*>(someIntPtr)->aMember
is without any runtime context undefined (a), while int i = bar(); i /= i;
could result in undefined behaviour (b) depending on the runtime evaluation of bar()
(which could return zero).
I only expect the (a) cases to be caught, not necessarily the (b) cases.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定你的目标在计算上是否可行。
但是,您可以使用
-Wall -Wextra -Werror
获得适度的接近;查看其他警告选项以了解您还想启用哪些功能。I'm not sure that your goal is computationally feasible.
However, you'll get moderately close with
-Wall -Wextra -Werror
; look at the other warning options to see what else you want to enable.不可能的。有很多很多无法检测到的 UB 实例。这可以说是它们成为 UB 的原因,正是因为在编译时不可能捕获这些问题。
一些示例:
int n = 0; std::cin>> n; ++n;
有符号溢出为 UB。 (值依赖的 UB 示例。)double d = std::sin(some_user_value); int n = d;
UB 如果d
不能表示为int
。 (同上。)编译多个翻译单元,每个翻译单元具有不同的可见类定义。 (由于编译模型的限制而导致的 UB 示例。)
任何竞争条件都被定义为 UB。 (与内存模型相关的 UB 示例。)
滥用可变参数函数。 (由于类型系统而导致 UB 的示例。)
Impossible. There are many, many instances of UB which are not detectable. That's arguably the reason why they are UB, exactly because it is impossible to catch these problems at compile time.
Some examples:
int n = 0; std::cin >> n; ++n;
Signed overflow is UB. (Example of value-dependent UB.)double d = std::sin(some_user_value); int n = d;
UB ifd
cannot be represented as anint
. (Ditto.)compile multiple translation units with differing class definitions visible to each. (Example of UB due to limitations of the compilation model.)
any race condition is by definition UB. (Example memory-model related UB.)
misuse of variadic functions. (Example of UB due to the type system.)
您可以使用类似于经典
lint
的静态代码分析工具。您可能已经有 cppcheck。You can use static code analysis tools similar to the classic
lint
. You may already have cppcheck.你不能,也不应该依赖编译器为你指出 UB。
最好的办法是使用
-Werror
使所有警告变成错误,并且 然后启用大量警告。You can't, and you shouldn't rely on the compiler to point out UB for you.
You best bet is to use
-Werror
to cause all warnings to become errors, and then enable a great deal of warnings.