1

I have the following set of macros (which I got from the first answer for How can I use the compile time constant __LINE__ in a string?) defined in an attempt to have a macro 'LOCATION_PREFIX' that I can use to "capture" the location of a line of code (will be passed to other functions that will perform logging).

#define STRINGIZE(f,l) STRINGIZE2(f) "(" STRINGIZE2(l)"):"
#define STRINGIZE2(x) #x
#define LOCATION_PREFIX STRINGIZE(__FILE__, __LINE__)

int main(){

printf("%s here\n", LOCATION_PREFIX);
printf("%s over here\n", LOCATION_PREFIX);

return 1;
}

Output:

"t.cpp"(8): here
"t.cpp"(9): over here

I want the output to be:

t.cpp(8): here
t.cpp(9): over here

Any help is greatly appreciated !

1 Answer 1

4

You don't need the first STRINGIZE2 invocation, as the file name is already a quoted string:

#define STRINGIZE(f,l) f "(" STRINGIZE2(l) "):"
#define STRINGIZE2(x) #x
#define LOCATION_PREFIX STRINGIZE(__FILE__, __LINE__)

int main(){
  printf("%s here\n", LOCATION_PREFIX);
  printf("%s over here\n", LOCATION_PREFIX);

  return 1;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Cheers ! Works perfectly, thank you very much for the quick response... will accept the answer as soon as I can.
Notice, that you then can also drop the f argument of STRINGIZE and directly put __FILE__ in there. I didn't do it so there's a clear relation to your code, though.
made the change to remove the passing of FILE, STRINGIZE now only takes (l).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.