编译器预处理期间的数学运算 [英] Mathematical operations during compiler preprocessing

查看:130
本文介绍了编译器预处理期间的数学运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常遇到这样的情况,我需要在编译时使用位移位和屏蔽操作生成几个常量.

I often have the situation where I need several constants generated at compile time for the use of bit shift and masking operations.

例如

#define blockbits 8
#define blocksize 256   // could be generated from 2^blockbits
#define blocksize 0xFF  // could be generated from blocksize - 1

我希望所有这些都是从blockbits生成的,但是据我所知,没有可以在预处理器中使用的电源操作.

I would like all these to be generated from blockbits, however there is no power operation that can be used in the preprocessor that I am aware of.

有人知道在编译时生成这种东西的简单方法吗?

Does anyone know a simple way of generating this sort of thing at compile time?

推荐答案

您可以将它们定义为数学表达式:

You can define them as mathematical expressions:

#define blockbits 8
#define blocksize (1 << blockbits) 
#define blockXXXX (blocksize - 1) // changed from blocksize to blockXXXX, since blocksize is already taken

括号应确保在其他表达式中使用运算符时没有优先级问题.

The parentheses are to make sure there are no operator precedence issues when you use them in other expressions.

您可能还想将名称更改为所有大写字母,例如BLOCKBITSBLOCKSIZE等,这是一种C ++命名约定,用于区分宏和普通名称.

You also might want to change the names to all uppercase like BLOCKBITS, BLOCKSIZE, etc, which is a C++ naming convention to distinguish macros from normal names.

这篇关于编译器预处理期间的数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆