Kallel Omar
Kallel Omar

Reputation: 1218

concatenate prefix in the function name with macro?

I want to concatenate some macro in the beginning of function name:

#include <stdio.h>

#define PFX mypfx

int PFX##_call() {
    printf("teeeeeeeeest");
}

int main(void)
{
    mypfxcall();
}

The above code return error in compilation.

How to add prefix with macro in the function name?

Upvotes: 1

Views: 2065

Answers (3)

Koldar
Koldar

Reputation: 1407

I don't know why you would want to do this (maybe because you want to "emulate" namespaces), but assuming you're in C, you can achieve it with the following code.

#define concat2(X, Y) X ## Y
#define concat(X, Y) concat2(X, Y)
#define pfx(x) concat(pfx_, x)

Usage:

int pfx(sum)(int x, int y) {
    return x + y;
}

int main() {
    printf("%d\n", pfx(sum)(5,4));
}

Note: if you want to use more macro processing power (i don't know if it's you case) you should visit P99

Upvotes: 4

Jabberwocky
Jabberwocky

Reputation: 50775

The ## operator only allows you to concatenate two strings inside another macro definition.

But this:

int PFX##_call()

is not a macro definition, therefor it will expand to this which is invalid C:

int mypfx##_call()

Example of valid usage:

#define FOO 1
#define BAR 2
#define FB FOO##BAR    // FB will expand to FOOBAR
                       // independently of the macros FOO and BAR

#define BF FOO BAR     // BF will expand to 1 2

Upvotes: 3

Paul Evans
Paul Evans

Reputation: 27567

Why don't you use a namespace instead:

namespace mypfx
{
    int call() {
         printf("teeeeeeeeest");
    }
}

int main(void)
{
    mypfx::call();
}

Upvotes: 1

Related Questions