'How can I get __LINE__ as a string constant? [duplicate]
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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ben |
