Question

I want to generate different named function useful for writing unit test cases. I want to do this basically to give unique name to each unit test case.

I am using google test framework for writing unit test cases. I have to use TEST_Macro to write unit test cases. I want to automatically give incrementing numbers to every unit test.

Here is my (non-working) code:

#include <iostream>
using namespace std;

#define join(x, y) x## y

void join(test, __COUNTER__)()
{
    cout << "\n 1";
}

void join(test, __COUNTER__)()
{
    cout << "\n 2";
}

int main()
{
    cout << "Hello world!" << endl;

     test0() ;
     test1() ;

    return 0;
}

What is the correct way to generate unique function names using __COUNTER__?

Was it helpful?

Solution

So this is the old "paste happens before evaluation of macro arguments", so you get test__COUNTER__ instead of test0.

You need to do a nested macro:

#define expandedjoin(x,y) x##y
#define join(x, y) expandedjoin(x, y)

(The rest of your code gives lots of errors because you are passing a void function to cout, which isn't good)

Complete working code:

#include <iostream>
using namespace std;
#define expandedjoin(x,y) x##y
#define join(x, y) expandedjoin(x, y)

void join(test, __COUNTER__)()
{
    cout << "\n 1";
}

void join(test, __COUNTER__)()
{
    cout << "\n 2";
}

int main()
{
    cout << "Hello world!" << endl;

    test0();
    test1();

    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top