我希望使用C预处理程序生成一系列随机数,并将它们存储在变量中供程序使用。
目标:
每次构建程序时,我都希望生成一个“独特”的随机数集。其中一小部分存储随机数的变量将被重写为有意义的(即非随机的)数字。我希望无论黑客如何调试程序或比较多个构建版本,都无法区分有意义的数字和随机数字。我希望构建过程自动化且自包含。我希望实现能够在Visual Studio和GCC之间移植。
澄清:
- 计算必须在编译时完成,而不是在程序执行时完成。任何调试程序的人应该只能看到一个变量被初始化为一个常量(即随机数)。
- 随机数应为整数。
- 随机数生成器应该以某种方式从
__DATE__
和__TIME__
进行种子处理,以便不同的构建会产生不同的随机数。 - 最好能够指定随机数的范围(例如从1到100),但这不是绝对必要的。
- 最好能够指定要生成的随机数的总数(例如声明1000个变量并将每个变量初始化为随机数),但这也不是绝对必要的。
到目前为止的尝试:
- Previous thread on arithmetic in the preprocessor: Can the C preprocessor perform integer arithmetic? The take-away is that the #if condition can evaluate arithmetic.
- Googling reveals that besides arithmetic, shift and bit operations can also be evaluated by the #if. I have confirmed this with Visual Studio C++.
Candidates for simple random number generators: http://www.ciphersbyritter.com/NEWS4/RANDC.HTM#369B5E30.65A55FD1@stat.fsu.edu Any one of these generators, or any generator that is impossible to reverse engineer from a given series of random numbers, would be fine because I don't need a particularly well behaved generator. For the sake of this exercise, we can use the following as an example:
unsigned long jcong=380116160; #define CONG (jcong=69069*jcong+1234567)
I think the basic problem is that there is state that is stored in the variable jcong between successive calls to the generator. Variable assignment is not supported in the preprocessor, as far as I know. Perhaps there is some clever recursive macro that can do the trick?
The closest I could get, but not satisfying my objective of being performed by the preprocessor, is:
unsigned long jcong=380116160; unsigned long randomBlock[] = {jcong=69069*jcong+1234567, jcong=69069*jcong+1234567};
I have confirmed in Visual Studio C++ that this does indeed initialize the array members to different random numbers. However, the debugger still steps through the initialization.