且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C预处理器生成一个随机数

更新时间:2023-02-06 08:54:18

我想问您一个问题,您想要一种通过预处理器创建唯一标识符令牌的方法.

I take your question that you want to have a way of creating unique identifier tokens through the preprocessor.

gcc具有一个名为__COUNTER__的扩展名,它可以实现您期望的名称.您可以将其与宏串联##结合使用以获得唯一标识符.

gcc has an extension that is called __COUNTER__ and does what you expect from its name. You can combine this with macro concatenation ## to obtain unique identifiers.

如果您使用的是C99编译器,则可以使用 P99 .它具有称为P99_LINEIDP99_FILEID的宏.它们可以用作

If you have a C99 compiler you can use P99. It has macros called P99_LINEID and P99_FILEID. They can be used as

#include "p99_id.h"

P99_LINEID(some, other, tokens, to, make, it, unique, on, the, line)

,并且与P99_FILEID类似.

第一个选项会根据您的令牌和行号以及一个哈希值(该哈希值取决于文件"p99_id.h"的包含次数)来处理.第二个宏仅使用该哈希而不是行号,以便在同一编译单元内的多个位置重现名称.

The first mangles a name from your tokens and the line number and a hash that depends on the number of times the file "p99_id.h" had been included. The second macro just uses that hash and not the line number such that a name is reproducible at several places inside the same compilation unit.

这两个宏还具有对应的P99_LINENOP99_FILENO,它们只产生大量数字而不是标识符令牌.

These two macros also have counterparts P99_LINENO and P99_FILENO that just produce large numbers instead of identifier tokens.