Can __FILE__ and __LINE__ be made linkable when pr

2020-07-06 07:36发布

问题:

Header:

#define TRACE_ERROR(s)                      \
{
  ...
  char TraceBuffer[512];
  sprintf(TraceBuffer, "%s\t(%s:%d)", s, __FILE__, __LINE__);
  DebugErrTrace(TraceBuffer);
  ...
}

Implementation:

void DebugErrTrace(char *String, ...) {
  ...
  qDebug() << String;
}

The above spits out a line of debug trace, which might look something like

ERROR File Missing! (..\trunk\Common\FileManager.cpp:102)

in Qt Creator's debug console.

I've noticed that Qt's own error messages e.g.

Object::connect: No such slot cClass::Method(QString) in ..\trunk\Components\Class.cpp:301

create what looks like a hyperlink around the __FILE__:__LINE__ part of the debug line, linking to the line which caused the problem. Is there any way I can I do this with my own debug output?

Cheers, Sam

回答1:

According to Qt Creator source code (there), the hyperlinks are only created for lines matching these regular expressions:

"^(?:\\[Qt Message\\] )?(file:///.+:\\d+(?::\\d+)?):"
"Object::.*in (.*:\\d+)"
"ASSERT: .* in file (.+, line \\d+)"
"^   Loc: \\[(.*)\\]"

So the simplest lines you could construct look like this:

qWarning("file:///%s:%i: %s", __FILE__, __LINE__, "your message");
qWarning("   Loc: [%s:%i] %s", __FILE__, __LINE__, "your message");

Qt Creator doesn't seem to care if the path after "file:///" is absolute or not.



回答2:

In addition to alexisdm's answer (which helped me very much, big thanks!):

Instead of defining a custom macro, I would suggest to do the following in newer versions of Qt and use qDebug itself:

qSetMessagePattern("%{if-category}%{category}: %{endif}%{message}\n   Loc: [%{file}:%{line}]");

The part before \n is Qt's default message pattern, and splitting with \n has the benefit that the log messages also can contain characters like [ or ] without messing up the links.

The message pattern can easily be extended with other log details like timestamps, thread id and so on, see the documentation. When adding other details, keep the link in a seperate line to avoid issues with Qt Creator's parsing.