Is there widely-available wide-character variant of `__FILE__`?

后端 未结 5 769
名媛妹妹
名媛妹妹 2020-12-18 22:36

One may generally use __LINE__ and __FILE__ in C++ programs, with many toolchains, including GCC.

__LINE__ under GCC evaluates

相关标签:
5条回答
  • 2020-12-18 22:56

    I would have put this answer as a comment to an earlier reply but was not allowed due to not having the minimum 50 reputation to comment...

    In Visual Studio, _T(__FILE__) will NOT expand to L__FILE__ unless you modify its standard definition of _T in the tchar.h header file. _T(__FILE__) and _T(__FUNCTION__) worked 5 years ago and still work today if you are looking for wide versions of the current file and function.

    _T(x) is defined as __T(x), which is defined as L##x when _UNICODE is defined and x otherwise. So _T(__FILE__) expands to something like __T("my_file.c"), which then expands to L"my_file.c" or "my_file.c" depending on _UNICODE. It is useful to test things before claiming that they do not work.

    0 讨论(0)
  • 2020-12-18 23:03

    You can make your own WFILE:

    #define WIDE2(x) L##x
    #define WIDE1(x) WIDE2(x)
    #define WFILE WIDE1(__FILE__)
    
    0 讨论(0)
  • 2020-12-18 23:04

    For example use const auto name = L"" __FUNCTION__;

    0 讨论(0)
  • In Visual Studio just surround it with _T(), for example:

    TRACE( _T("function = %s"), _T(__FUNCTION__);
    
    0 讨论(0)
  • 2020-12-18 23:09

    Use:

    WIDE(MEXPAND(__FILE__))
    

    and

    WIDE(STRINGIFY(__LINE__))
    

    or replace __LINE__ with anything that needs to be stringified, and replace __FILE__ with any macro string literal you want to widen.

    Using the following definitions:

    #define STRINGIFY2(m) #m
    #define MEXPAND(m) m
    #define STRINGIFY(m) STRINGIFY2(m)
    #define WIDE(m) L ## m
    

    Example usage:

    #define AssertBreakMethod DebugBreak
    
    #define AssertBreakForce(expr) \
      do \
      { \
        if (!(expr)) \
        { \
          OutputDebugStringW(WIDE(MEXPAND(__FILE__)) \
              WIDE("(") WIDE(STRINGIFY(__LINE__)) \
              WIDE("): Assertion failed: ") \
              WIDE(#expr) WIDE("\n")); \
          AssertBreakMethod(); \
        } \
      } \
      while (0)
    

    Note that the whole parameter to OutputDebugString is assembled statically at compile time into a single string literal.

    The trick with stringification of a macro is passing it through another macro. When __FILE__ is passed to MEXPAND it is expanded at that time. MEXPAND returns its argument which is now a string. It is then legal to put the leading L there to make it wide.

    STRINGIFY does the same trick, it passes its argument through STRINGIFY2 which expands the argument to the line number (which looks like an integer at that point) then STRINGIFY2 puts the # symbol before it, stringifying the integer.

    0 讨论(0)
提交回复
热议问题