views:

92

answers:

2

I have the following couple of C pre-processor macros for creating test functions:

// Defines a test function in the active suite
#define test(name)\
    void test_##name();\
    SuiteAppender test_##name##_appender(TestSuite::active(), test_##name);\
    void test_##name()

which is used like this:

test(TestName) {
    // Test code here
}

and

// Defines a test function in the specified suite
#define testInSuite(name, suite)\
    void test_##name();\
    SuiteAppender test_##name##_appender(suite, test_##name);\
    void test_##name()

which is used like this:

test(TestName, TestSuiteName) {
    // Test code here
}

How can I remove the duplication between the two macros?

+5  A: 
#define test(name) testInSuite( name, TestSuite::active() )

However this doesn't reduce the amount of emitted C and machine code, only removes logical duplication.

sharptooth
Does this work? I thought that the preprocessor expanded macros in a single pass...
Matthew Murdoch
Whoops, args wrong way round!
Skizz
@Matthew: Macros are expanded while it is possible, not in a single pass, so chains of dependent macros are possible and can be used for creating barely debuggable code.@Skizz: True, fixed that.@Neil Butterworth: True about the emitted code, and I agree with you that this problem could hardly be solved. But logical duplication is elegantly removed.
sharptooth
I thought I'd tried this already without success but I was obviously confused! If you remove the trailing semi-colon I'll accept this answer. Thank you.
Matthew Murdoch
also important, a macro can't be replaced by itself: #define X(A) X(A) won't cause an infinite recursion :)
Johannes Schaub - litb
A: 

Try:

#define test(name) testInSuite (name, TestSuite::active())

Skizz

Skizz