编译器预处理过程中的数学操作

Mathematical operations during compiler preprocessing

本文关键字:操作 预处理 过程中 编译器      更新时间:2023-10-16

我经常会有我需要在编译时间生成的几个常数以使用位移动和掩盖操作。

,例如

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

我希望从blockbits生成所有这些,但是我知道的预处理器中没有可以使用的功率操作。

有人知道在编译时间生成这种事情的简单方法吗?

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

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

括号是为了确保在其他表达式中使用时没有操作员优先问题。

您可能还想将名称更改为所有大写,例如BLOCKBITSBLOCKSIZE等,这是C 命名约定,以区分宏与正常名称。

如果要使用const而不是#define's,并且如果要制作一个通用的功率函数(不仅仅是2个幂),该功能会在运行时计算值,您也可以尝试使用这样的模板进行操作:

template<int num, int pow> struct temp_pow
{
    static const unsigned int result=temp_pow<num, pow-1>::result*num;
};
template<int num> struct temp_pow<num, 1>
{
    static const unsigned int result=num;
};
const int BLOCKBITS = 8;
const int BLOCKSIZE = temp_pow<2,BLOCKBITS>::result;   // could be generated from 2^BLOCKBITS
const int BLOCKSIZE_1 = BLOCKSIZE-1;