gpt4 book ai didi

c++ - VS 2015 在预处理中使用 CLOCKS_PER_SEC 破坏代码

转载 作者:太空狗 更新时间:2023-10-29 20:56:16 27 4
gpt4 key购买 nike

我正在将我的旧代码库移植到 VS 2015。代码是:

#if XYZ 
....
#elif CLOCKS_PER_SEC > 999 //<< Getting error here.
...
#endif

我在 CLOCKS_PER_SEC 行遇到错误:

Severity    Code    Description 
Error C1012 unmatched parenthesis: missing ')'

查看 time.hCLOCKS_PER_SEC 的定义

// The number of clock ticks per second
#define CLOCKS_PER_SEC ((clock_t)1000)

所以,看起来是因为 clock_t,因为预处理器宏不能使用它。

请建议我该如何解决?

最佳答案

C 语言规范在 7.1.4/1 中指出

All object-like macros listed as expanding to integer constant expressions shall additionally be suitable for use in #if preprocessing directives.

但是,宏 CLOCKS_PER_SEC 未列为整型常量表达式 (7.27.1/2)。这意味着它不能在 #if 下移植使用。

这正是您刚刚遇到的情况。您应该开发一种替代方法来在您的代码中实现条件编译。在一般情况下,CLOCKS_PER_SEC 不能与 #if 一起使用。语言标准要求 CLOCKS_PER_SEC 具有 clock_t 类型,而不是 int 类型,这意味着转换在那里是完全合理的。

P.S. 请注意,您当前对 CLOCKS_PER_SEC 的定义 确实 符合整数常量表达式的条件,但 #if 强加了对条件表达式的一些额外要求。即,不允许转换。

P.P.S. 在 C99 的原始版本中,CLOCKS_PER_SEC 被描述为一个常量 表达式。但是,在 C99+TC2 中,“常量”一词不再存在。它被删除是为了消除上述要求之间的矛盾:1) 常量表达式宏在 #if 下可用,这排除了强制转换,以及 2) CLOCKS_PER_SEC 具有 clock_t 类型,只能通过强制转换实现。可以在此处找到相应的缺陷报告:http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_281.htm

关于c++ - VS 2015 在预处理中使用 CLOCKS_PER_SEC 破坏代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33993032/

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