George R
George R

Reputation: 3860

Nested macro expansion

I'm not sure if that's the right terminology to use, however my problem is that the a macro call ("PLUGIN_NAME") as a parameter to another macro call ("IMPLEMENT_MODULE"), which in turn prints it as a string, prints that argument as the macro call ("somePLUGIN_NAME") rather than the expanded result ("someSomePluginName").

Note that "IMPLEMENT_MODULE" is an API call so I can't change that.

#define IMPLEMENT_MODULE(name) something##name

#define PLUGIN_NAME SomePluginName
#define _STR(s) #s
#define STR(s) _STR(s)
#define PLUGIN_NAME_STR STR(PLUGIN_NAME)

int main()
{
    string expected = "somethingSomePluginName";
    string actual = STR(IMPLEMENT_MODULE(PLUGIN_NAME));

    printf("expected: %s || actual: %s\n", expected.c_str(), actual.c_str());
    assert(expected == actual);
}

I've put it here: http://codepad.org/FRzChJtD

Upvotes: 6

Views: 9680

Answers (1)

namezero
namezero

Reputation: 2293

You need another helper macro to concatenate the preprocessor tokens after macro-expanding them:

#define IMPLEMENT_MODULE_2(A, B) A##B
#define IMPLEMENT_MODULE(name) IMPLEMENT_MODULE_2(something, name)

See working example here

This technical explanation is that macro expansion will not occur if the token-pasting (##) or stringizing operator (#) are found by the preprocessor.

Upvotes: 7

Related Questions