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

后端 未结 8 2078
旧巷少年郎
旧巷少年郎 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:35

    His goal is to create a macro (named logError) that will automatically include the symbols necessary and do the string concatenation within the preprocessor, only using string literals.

    So, combining the basically-correct answers answers thus far, let's write the macro:

    #define STRINGIZE_DETAIL(x) #x
    #define STRINGIZE(x) STRINGIZE_DETAIL(x)
    #define logError(msg) (__FILE__ " line " STRINGIZE(__LINE__) ": " msg)
    

    You can then use this macro anywhere to create a generic error message code in string literal format at compile time.

    Note: You can also use __FUNCTION__ (or an equivalent, it varies by compiler) instead of __FILE__, if you prefer, to keep track of the function name instead of the file name.

提交回复
热议问题