最近Googletest中的ColoredPrintf

问题描述

我当时使用的是GoogleTest的过时版本,并且曾使用hack进行自定义打印,请参见:How to send custom message in Google C++ Testing Framework?

我的资源包含来自上面链接的以下代码

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)

我已将项目中的GoogleTest源更新为主版本,现在出现链接错误提示未定义ColoredPrintf。

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

研究新鲜的gtest.cc表明他们已经将GTestColor更改为枚举类,并将其放入命名空间testing::internal中的匿名命名空间中: https://github.com/google/googletest/blob/master/googletest/src/gtest.cc#L3138

我已将源代码中的代码段更改为:

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

        extern void ColoredPrintf(GTestColor color,...);
    }
}

作为快速解决方案,我在namespace { ... }的{​​{1}}附近删除GTestColor

问题:是否可以避免编辑gtest.cc而仍然可以使用其功能

解决方法

您不能访问编译单元外部的匿名名称空间中的成员。另请参见this question

取决于您的用例的替代方案可能是:

  • 使用event listeners替换标准输出。
  • 通过修改输出的脚本将输出插入管道。
  • 让Google Test生成XML或JSON报告并基于XML / JSON报告生成输出。