开发者

using #defines and passing functions to them

开发者 https://www.devze.com 2022-12-17 20:26 出处:网络
gcc 4.4.2 c89 I re-engineering some code in c8开发者_StackOverflow中文版9. However, I am totally confused with the code that uses the following #defines. So I created a small application that maybe I

gcc 4.4.2 c89

I re-engineering some code in c8开发者_StackOverflow中文版9. However, I am totally confused with the code that uses the following #defines. So I created a small application that maybe I would understand more of how this is working.

From what I can gather the MODULE_API will pass a function name and call the macro MODULE_SOURCE_API and concatenate name and func. So I create a simple function called print_name and ran the code. I got the following error messages:

implicit declaration of function ‘print_name’
undefined reference to `print_name'

What would be the main reason for doing this?

#include <stdio.h>

#define MODULE_SOURCE_API(name, func) name##_##func
#define MODULE_API(func) MODULE_SOURCE_API(mod_print, func)

void MODULE_API(print_name)(const char const *name);

int main(void)
{
    printf("=== Start program ===\n");

    print_name("Joe bloggs");

    printf("== End of program ===\n");

    return 0;
}

void MODULE_API(print_name)(const char const *name)
{
    printf("My name is [ %s ]\n", name);

}

Many thanks for any advice,

EDIT ==== I have just made a correction I should be calling

MODULE_API(print_name)("Joe Bloggs");

But how can I print out what will be the outcome of concatenating? And what is the reason for doing this?

Many thanks,


#define MODULE_SOURCE_API(name, func) name##_##func
#define MODULE_API(func) MODULE_SOURCE_API(mod_print, func)

 void MODULE_API(print_name)(const char const *name);

That will be producing a function named mod_print_print_name instead of print_name

You can check it on gcc with the -E option.

gcc -E ak.c gives

/* ...... */
void mod_print_print_name(const char const *name);

int main(void)
{
   printf("=== Start program ===\n");

   print_name("Joe bloggs");

   printf("== End of program ===\n");

   return 0;
}

void mod_print_print_name(const char const *name)
{
   printf("My name is [ %s ]\n", name);

}


You can try to manually expand the macros to understand what is going on:

void MODULE_API( print_name )( const char * name ); // the second const there is redundant
                 // maybe you meant 'const char * const??

=(expand MODULE_API)=>

void MODULE_SOURCE_API( mod_print, print_name )( const char* name );

=(expand MODULE_SOURCE_API)=>

void mod_print_print_name( const char *);

As you see, the function being declared (and defined at the end of the code) is not print_name, but rather mod_print_print_name. Go back to the initial code and see how the macro is intended to be used. I would assume that function calls are performed with the same macros that are used for declarations and definitions.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号