7

I'm trying to know in a function its caller name.

If you look to the following link, it's not duplicated because I add a difference: the ellipsis usage in function declaration.

I've tried to do, starting from this solution How can we know the caller function's name? to do that, but I cannot get the solution.

This works to me:

void a(int deb, char *str)
{
    printf("%s\n", str);
}

void a_special(int deb, char const * caller_name, char *str)
{
    printf( "[%d] blablabla [%s] ", deb, caller_name);
    a(deb, str);
}

#define a(deb, str) a_special(deb, __func__, str)

int main()
{
    a(1, "my log");
    return 0;
}

But when I add the ellipsis (I say: "...") I don't know how to achieve it with the macro definition. Is possible in standard-C?

void a(int deb, char *str, ...) 
{
    va_list args;
    va_start(args,str);
    vprintf(str,args);
    va_end(args);
}

void a_special(int deb, char const * caller_name, char *str, ...) 
{
    printf( "[%d] blablabla [%s] ", deb, caller_name);
    a(deb, str, ...); 
}

#define a(deb, str) a_special(deb, __func__, str)

int main()
{
    a(1, "mylog %d %s", 1, "param2");
    return 0; 
}

I've also tried to get it using backtrace compiling with -rdynamic without success, but anyway I'd prefer to know how to include ellipsis (3 dots) in macro. Thanks in advance!

Alejandro Galera
  • 3,445
  • 3
  • 24
  • 42
  • 2
    So your question is... how to forward a variable argument list to a function? – StoryTeller - Unslander Monica Jan 09 '19 at 13:08
  • 1
    _"but anyway I'd prefer to know how to include ellipsis (3 dots) in macro."_ The answer to that is use inside the macro `__VA_ARGS__`. And as parameter for the macro, you can pass the macro also `...`. So, `#define a(deb, str, ...) a_special(deb, __func__, str, __VA_ARGS__)`. – Duck Dodgers Jan 09 '19 at 13:11
  • 1
    Some good C programming practice: 1) avoid variadic functions 2) avoid variadic macros 3) avoid function-like macros. Combining all these 3 cases of bad practice is not a brilliant idea. – Lundin Jan 09 '19 at 14:22

1 Answers1

7

If all you are asking for is how to forward the ellipses on to the macro and then from the macro to the function, then the following should be sufficient.

Basically, you pass the macro also the ellipses ... and inside the macro you can use __VA_ARGS__.

void a(int deb, char *str, ...)
{
    va_list args;
    va_start(args,str);
    vprintf(str,args);
    va_end(args);
}

void a_special(int deb, char const * caller_name, char *str, ...)
{
    printf( "[%d] blablabla [%s] ", deb, caller_name);
    a(deb, str);
}

#define a(deb, str, ...) a_special(deb, __func__, str, __VA_ARGS__)

int main()
{
    a(1, "mylog %d %s", 1, "param2");
    return 0;
}
Duck Dodgers
  • 3,409
  • 8
  • 29
  • 43