Why do you even need it as a string? What's wrong with an integer? Here are two ways you could write logError()
:
#define logError(str) fprintf(stderr, "%s line %d: %s\n", __FILE__, __LINE__, str)
// Or, forward to a more powerful function
#define logError(str) logError2(__FILE__, __LINE__, str)
void logError2(const char *file, int line, const char *str);
If you really need the line as a string, you can use the stringizing operator #
, but because of the way macros work, you'll need to wrap it in two macros:
#define STRINGIZE(x) STRINGIZE2(x)
#define STRINGIZE2(x) #x
#define LINE_STRING STRINGIZE(__LINE__)
And now LINE_STRING
is a macro that will expand to a string containing the current line number wherever it is expanded. If you only had one level of macros (i.e. if you had #define STRINGIZE(x) #x
), then you would get the literal string "__LINE__"
every time you expanded it, which is not what you want.