How to generate function name using c macro

The macro "VER" is defined as "((u_long) 1)" in another header file that I cannot change.

In my code I need to write the function "test_1" using "test" and VER. However, the compiler reported an error because "test_ ((u_long) 1)" was created instead of "test_1".

My question is: How to write a macro so that it can generate "test_1"?

Thanks in advance!

#define VER ((u_long)1) /* This is defined in some other header file which I can't change*/ #define paste(x, y, z) x ## y ## z #define paste2(x, y, z) paste(x, y, z) #define fcall(fname) paste2(fname, _, VER) int test_1() { return 0; } int main() { fcall( test )(); return 0; } 
+4
source share
3 answers

I cannot guarantee this is 100% portable, but it should work:

 #define VER ((u_long)1) #define STRIP1(x) STRIP2 x #define STRIP2(x) STRIP3 x #define STRIP3(x) #define paste(x, y, z) x ## y ## z #define paste2(x, y, z) paste(x, y, z) #define fcall(fname) paste2(fname, _, STRIP1(VER)) 

Living example

It works by interpreting parentheses inside a VER definition as a macro definition. Here are some expansions, as they arise:

 STRIP1(VER) // STRIP1 with argument VER STRIP2 ((u_long)1) // STRIP2 with argument (u_long)1 STRIP3 (u_long)1 // STRIP3 with argument u_long, followed by 1 1 

If we reinstall the spaces (in any case, this is negligible), we get the following:

 STRIP1(VER) STRIP2((u_long) 1) STRIP3(u_long) 1 1 
+5
source

With this source, you probably won’t be able to, as the macro extension is textual, so ((u_long)1) cannot become 1 .

One solution, of course, would be to actually write some code to print the actual VER value. Another alternative is to convince the people who own the file that you cannot change that they need to change it for you ...

0
source

In a modified version of Angew

 #define VER ((u_long)1) #define _(x) x #define id(x) _(x) #define STRIP3(x) #define STRIP2(x) id(STRIP3 x) #define STRIP1(x) id(STRIP2 x) #define paste(x, y, z) x ## y ## z #define paste2(x, y, z) paste(x, y, z) #define fcall(fname) paste2(fname, _, STRIP1(VER)) 
0
source

Source: https://habr.com/ru/post/1492917/


All Articles