C preprocessor stringification weirdness
Asked Answered
C

2

5

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?

Cort answered 12/9, 2011 at 12:15 Comment(2)
You might find these answers helpful.Parasympathetic
The C++ FAQ has an item on this, and even says "Try concatenating a symbol with LINE and see what happens then.": parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6Hiltonhilum
C
8

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).

Chilton answered 12/9, 2011 at 12:56 Comment(0)
M
3

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.

Meijer answered 12/9, 2011 at 12:27 Comment(3)
Yes, but you don't really explain why it doesn't work with another macro.Chilton
Because that's the rule. There's really nothing more to it.Kruse
But what is the rule and why does it exist...? (yes, there is a very good reason for it).Chilton

© 2022 - 2024 — McMap. All rights reserved.