Generate a random number using the C Preprocessor

后端 未结 3 816
暖寄归人
暖寄归人 2020-12-09 18:00

I would like to generate a random number or string using the C Preprocessor ... um ... I don\'t even know if this is possible, but I am trying to create var

3条回答
  •  再見小時候
    2020-12-09 18:52

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

    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.

    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)
    

    and similarily for P99_FILEID.

    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.

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

提交回复
热议问题