How can I generate unique values in the C preprocessor?

后端 未结 6 1154
南笙
南笙 2020-11-27 04:54

I\'m writing a bunch of related preprocessor macros, one of which generates labels which the other one jumps to. I use them in this fashion:

MAKE_FUNNY_JUMPI         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 05:28

    As others noted, __COUNTER__ is the easy but nonstandard way of doing this.

    If you need extra portability, or for other cool preprocessor tricks, the Boost Preprocessor library (which works for C as well as C++) will work. For example, the following header file will output a unique label wherever it's included.

    #include 
    #include 
    
    #if !defined(UNIQUE_LABEL)
    #define UNIQUE_LABEL
    #define BOOST_PP_VALUE 1
    #include BOOST_PP_ASSIGN_SLOT(1)
    #undef BOOST_PP_VALUE
    #else
    #define BOOST_PP_VALUE BOOST_PP_INC(BOOST_PP_SLOT(1))
    #include BOOST_PP_ASSIGN_SLOT(1)
    #undef BOOST_PP_VALUE
    #endif
    
    
    BOOST_PP_CAT(my_cool_label_, BOOST_PP_SLOT(1)):
    

    Sample:

    int main(int argc, char *argv[]) {
        #include "unique_label.h"
        printf("%x\n", 1234);
        #include "unique_label.h"
        printf("%x\n", 1234);
        #include "unique_label.h"
        return 0;
    }
    

    preprocesses to

    int main(int argc, char *argv[]) {
        my_cool_label_1:
        printf("%x\n", 1234);
        my_cool_label_2:
        printf("%x\n", 1234);
        my_cool_label_3:
        return 0;
    }
    

提交回复
热议问题