Unexpected predefined macro behaviour when pasting tokens

前端 未结 3 719
囚心锁ツ
囚心锁ツ 2021-01-24 08:52

The following (test with gcc -E blah.c):

#define UNUSED(type) type UNUSED_ ## __COUNTER__
UNUSED(char const *)
UNUSED(int)

Generat

3条回答
  •  感情败类
    2021-01-24 09:19

    __COUNTER__ was only introduced in GCC 4.3 - if you happen to use an earlier version, the macro is simply not defined. In that case Boost.PPs BOOST_PP_COUNTER macro might be worth looking into.

    On newer GCC versions you still need a different approach to concatenation, as ## prevents its arguments from expanding. Thus you have to expand them first before using ##:

    #define CAT(a, b) CAT_I(a, b)
    #define CAT_I(a, b) CAT_II(a ## b)
    #define CAT_II(x) x
    #define UNUSED(type) type CAT(UNUSED_, __COUNTER__)
    

    If you're already using Boost, BOOST_PP_CAT() gives you the same functionality.

提交回复
热议问题