Search code examples
c++macrosboost-preprocessor

Keep track of macro expansion


I want to keep track of macro expansion - how many times the macro has been expanded and what are the args when expansion happened.

For example,

I have a macro might look like this:

#define mymacro(x) int x

and in my code I have something like this:

mymacro(a);
mymacro(b);

in the end of the preprocessor expansion (oh yeah, is there a way to make a specific macro to become the last to expand?), I would like to know how many times mymacro has been used and what are the args passed. In this case, it would be 2 times, and args would be a and b.

I was investigating boost-preprocessor lib. They have BOOST_PP_ARRAY, but I don't know how to make it "static", so that I can use it in later.

I found something in the BOOST_PP_COUNTER. It looks like the BOOST_PP_COUNTER is something that can maintain its state in preprocessor phrase. But I am still unclear how to do what I wanted.


Solution

  • How about something like this?

    #include <iostream>
    
    int m_counter = 0;
    const char *m_arguments[32] = { 0 };
    
    #define COUNT_M(a) m_arguments[m_counter++] = #a;
    #define M(a) COUNT_M(a) int a
    
    int main()
    {
        M(x);
        M(y);
    
        for (int i = 0; i < m_counter; i++)
        {
            std::cout << "m_arguments[" << i << "] = \"" << m_arguments[i] << "\"\n";
        }
    }