concat code with macro in C

风流意气都作罢 提交于 2020-01-07 07:42:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!