Is it possible to use the value of a define as part of an identifier?

120 views Asked by At

Is it possible to include a pre-defined id in an identifier?

The header:

/* myfile.h */
#define func MYID##_func
static void func() {}
#undef func

The c file:

/* myfile.c */
#define MYID FOO
#include "myfile.h"
#undef MYID

#define MYID BAR
#include "myfile.h"
#undef MYID

/* check the functions exist */
void main()
{
    FOO_func();
    BAR_func();
}

My aim here is to create 2 functions: (FOO_func, BAR_func).


I tried to compile the code above, and the functions are identified as MYID_func (which fails since there are 2 of them).

I could do:

#define func FOO_func
#include "myfile.h"
#undef func

... But this doesn't scale so nicely when the file has many identifiers, since they would all have to be defined first.


The goal is to be able to avoid naming collisions when the file is included multiple times in the same C file.

2

There are 2 answers

0
R Sahu On BEST ANSWER

You can use couple of layers of macros to accomplish what you want to.

/* myfile.h */
#define CONCAT2(A, B) A ## B
#define CONCAT(A, B) CONCAT2(A, B)
#define func() CONCAT(MYID, _func)()
static void func() {}
#undef func

You need the extra layers to make sure that MYID is expanded as a macro.

0
Mabus On

The operator ## don't expand macros. If you want to do that use an extra define:

#define CONCAT_AUX(MACRO_ARG1, MACRO_ARG2) MACRO_ARG1 ## MACRO_ARG2
#define CONCAT(MACRO_ARG1, MACRO_ARG2) CONCAT_AUX(MACRO_ARG1, MACRO_ARG2)

#define func CONCAT(MYID, _func)