Question

I am defining a macro that evaluates to a constant string, holding the filename and the line number, for logging purposes.

It works fine, but I just can't figure out why 2 additional macros are needed - STRINGIFY and TOSTRING, when intuition suggests simply __FILE__ ":" #__LINE__.

#include <stdio.h>

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define THIS_ORIGIN (__FILE__ ":" TOSTRING(__LINE__))

int main (void) {
  /* correctly prints "test.c:9" */
  printf("%s", THIS_ORIGIN);
  return 0;
}

This just seems like an ugly hack to me.

Can someone explain in detail what happens stage by stage so that __LINE__ is stringified correctly, and why neither of __FILE__ ":" STRINGIFY(__LINE__) and __FILE__ ":" #__LINE__ works?

Was it helpful?

Solution

Because of the order of expansion. The GCC documentation says:

Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified or pasted with other tokens. After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them.

So if the argument will be stringified, it is not expanded first. You are getting the literal text in the parenthesis. But if it's being passed to another macro, it is expanded. Therefore if you want to expand it, you need two levels of macros.

This is done because there are cases where you do not want to expand the argument before stringification, most common being the assert() macro. If you write:

assert(MIN(width, height) >= 240);

you want the message to be:

Assertion MIN(width, height) >= 240 failed

and not some insane thing the MIN macro expands to (in gcc it uses several gcc-specific extensions and is quite long IIRC).

OTHER TIPS

You can't simply use __FILE__":"#__LINE__ because the stringify operator # can only be applied to a macro parameter.

__FILE__ ":" STRINGIFY(__LINE__) would work OK with other text (eg __FILE__ ":" STRINGIFY(foo), but doesn't work when used with another macro (which is all __LINE__ really is) as the parameter; otherwise that macro doesn't get substituted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top