0

In C++ (or C) how can I get the line number (__LINE__) as a string?

In particular, I want a macro that magically has "example.cpp:14" on line 14 of example.cpp. C++ automatically combines juxtaposed string literals, so I just need __LINE__ as a string.

Ben
  • 9,184
  • 1
  • 43
  • 56
  • Once I had the solution, I realized it was a dup, but when I was searching, I had trouble with the specific question "How do I make `__LINE__` a string?". I'm fine with leaving this closed as a duplicate; hopefully it helps others find the solution. – Ben Feb 09 '22 at 20:40

1 Answers1

3

The trick to turning numerical constants into strings is the STR and XSTR macros, defined below:

#include <iostream>

//! See https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html
#define XSTR(a) STR(a)
#define STR(a) #a

#define LINE_AS_STR XSTR(__LINE__)
#define FILE_AND_LINE __FILE__ ":" LINE_AS_STR

int main() {
    constexpr const char* line = LINE_AS_STR;
    std::cout << "That was line \"" << line << "\"" << std::endl;
    std::cout << FILE_AND_LINE << std::endl;
}

output:

That was line "11"
example.cpp:13

https://godbolt.org/z/xzE1nWeMd

Ben
  • 9,184
  • 1
  • 43
  • 56