Pergunta

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 !

Foi útil?

Solução

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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top