Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get macro name __LINE__ for a multi-line macro call?

Tags:

c

gcc

macros

I have created a macro for error tracing. Here is a simplified version:

#include <stdio.h>

#define ERR(...)                                 \
    printf("error @ %d\n", __LINE__)

int main()
{
    return ERR(1,               /* line 7 */
               2,               /* line 8 */
               3);              /* line 10 */
}

When executed, it prints:

error @ 10

However, to match the printed line number with grep output (grep -n ERR test.c), I need line number of the ERR string (line 7).

Is such thing even possible? Any ideas?

Additional notes: the macro should look like a function call (so I can do return ERR(...);). The compiler is GCC version 4.4.5. C99 + GNU extensions can be used.

like image 439
LRipa Avatar asked Jan 18 '26 12:01

LRipa


2 Answers

Bases on @cwyang proposition, use macros with mismatched parenthesis in the definition and the coma operator.

#define ERR (LINEINFO, HANDLEARGS
#define HANDLEARGS(...) __LINE__)
#define LINEINFO printf("error @ %d: ", __LINE_)

return ERR(x,
           y,
           z);

will expand to

return (printf("error @ %d: ", 5), 7);

with gcc.

like image 126
AProgrammer Avatar answered Jan 21 '26 04:01

AProgrammer


How about the following:

#define VOID_MACRO(...) (void) 0
#define ERR printf("err @ %d\n", __LINE__); VOID_MACRO
like image 23
Chul-Woong Yang Avatar answered Jan 21 '26 04:01

Chul-Woong Yang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!