How can I use the compile time constant __LINE__ in a string?

后端 未结 8 2140
旧巷少年郎
旧巷少年郎 2021-01-31 10:41

I can use __LINE__ as a method parameter just fine, but I would like an easy way to use it in a function that uses strings.

For instance say I have this:

8条回答
  •  青春惊慌失措
    2021-01-31 11:37

    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.

提交回复
热议问题