ColoredPrintf in recent googletest

Viewed 580

I was using rather obsolete version of GoogleTest and have used hack for custom printing, found here: How to send custom message in Google C++ Testing Framework?

My sources contain the following code from the link above

namespace testing
{
 namespace internal
 {
  enum GTestColor {
      COLOR_DEFAULT,
      COLOR_RED,
      COLOR_GREEN,
      COLOR_YELLOW
  };

  extern void ColoredPrintf(GTestColor color, const char* fmt, ...);
 }
}
#define PRINTF(...)  do { testing::internal::ColoredPrintf(testing::internal::COLOR_GREEN, "[          ] "); testing::internal::ColoredPrintf(testing::internal::COLOR_YELLOW, __VA_ARGS__); } while(0)

I have updated sources of GoogleTest in my project to master version and now I have link errors saying that ColoredPrintf is not defined.

error LNK2019: unresolved external symbol "void __cdecl testing::internal::ColoredPrintf(enum testing::internal::`anonymous namespace'::GTestColor,char const *,...)" (?ColoredPrintf@internal@testing@@YAXW4GTestColor@?A0x313d419f@12@PEBDZZ) referenced in function

Studying fresh gtest.cc shows that they have changed GTestColor to enum class and put it into an anonymous namespace inside the namespace testing::internal: https://github.com/google/googletest/blob/master/googletest/src/gtest.cc#L3138

I've changed the snippet in my sources to:

namespace testing {
    namespace internal
    {
        enum class GTestColor { kDefault, kRed, kGreen, kYellow };

        extern void ColoredPrintf(GTestColor color, const char* fmt, ...);
    }
}

And as a quick fix I have removed namespace { ... } around GTestColor in gtest.cc.

The question: is it possible to avoid editing gtest.cc and still have access to their function?

1 Answers

You cannot access members in an anonymous namespace outside of the compilation unit. See also this question.

Depending on your use-case alternatives may be:

  • Use event listeners to replace the standard output.
  • Pipe the output through a script that modifies the output.
  • Have Google Test generate an XML or JSON report and generate output based on the XML/JSON report.
Related