问题
Here's the thing:
Let's say I have two function defined in C:
test_1() {};
test_2() {};
I would like to have a macro (e.g. NUM_TEST) that will refer to test number. Best way is to show it in code:
#define NUM_TEST 1
test_1() {};
test_2() {};
int main() {
test_ ## NUM_TEST ## ()
}
I would appreciate, if someone would help, to find a solution, how to concat name of function with macro.
EDIT:
To make it more clear. I would like to just by changing of "macro NUM_TEST" change invoked function between test_1() and test_2().
Yes I know there are more easier ways to do that, but this is just an example to more general problem: How to concat macro with text in C without adding new lines or new macro functions.
EDIT 2:
Obviously I was now clear enough. Let's say I wrote a program. It has two (or more) run types. I have one macro called NUM_TEST. By setting mentioned macro to 1 or 2 a want to choose run type between test_1() or test_2()
Thank you!
回答1:
Is this what you're looking for?
#include <stdio.h>
#define TEST(NUM) test_ ## NUM ()
test_1() { printf ("Hello "); }
test_2() { printf ("World!\n"); }
int main (void)
{
TEST(1);
TEST(2);
// Prints "Hello World!\n"
return 0;
}
回答2:
Rather than creating a Macro that determines this, it is better to just pass command line argument to it which represents the test number. Like this:
#include <stdio.h>
int main( int argc, char *argv[] )
{
switch(argv[1])
{
case "1" :
Test_1();
break;
case "2" :
Test_2();
break;
default :
printf("Test ID not found");
}
}
If you are, however, just looking to alias a name, you can have your functions Test_1, Test_2, etc. Then just have a generic TESTTORUN wherever you want the selected test to run. On compilation have the preprocessor replace it with the function name you want:
#define TESTTORUN Test_1 //Or Test_2 or whatever
This will cause the compiler to replace TESTTORUN everywhere in the program with Test_1.
来源:https://stackoverflow.com/questions/29020818/concat-code-with-macro-in-c