【问题标题】:Boost test unresolved external with static variable使用静态变量的外部升压测试未解决
【发布时间】:2015-11-26 20:34:09
【问题描述】:

好的,所以我已经查看了有关堆栈溢出问题的一些问题,但找不到任何可以完全回答我的问题的问题。

这是我在将 boost 测试项目与我的生产代码相关联时遇到的错误。我正在使用 MSVS-2013:

2 错误 LNK2001: 无法解析的外部符号 "private: static class std::shared_ptr Debug::_Debug" (?_Debug@Debug@@0V?$shared_ptr@VDebug@@@std@@A) C:\Code\ Main.Testing\B.obj
3 错误 LNK1120: 1 未解决的外部 C:\Code\Main.Testing\Debug\Main.Testing.exe

这是导致错误的代码:

调试.h:

#pragma once
#include <string>
#include <memory>
class Debug
{
    private:
    static std::shared_ptr<Debug> _Debug;

    public:
    static std::shared_ptr<Debug> Instance()
    {
        if (!_Debug)
        {
            _Debug.reset(new Debug);
        }

        return _Debug;
    }

    Debug() {}
    ~Debug() {}
    void Exit(std::string sMessage)
    {
        //Do stuff.
        return;
    }
};

调试.cpp:

#include "Debug.h"

std::shared_ptr<Debug> Debug::_Debug;

在单独的测试项目中测试文件 B.cpp:

#pragma once
#define BOOST_TEST_DYN_LINK

#include <boost\test\unit_test.hpp>
#include "<path-to-folder>/Debug.h"

BOOST_AUTO_TEST_SUITE(B)

BOOST_AUTO_TEST_CASE(testCaseB)
{
    Debug::Instance()->Exit("blah");
}

BOOST_AUTO_TEST_SUITE_END()

当我从上述文件中删除静态变量时,代码编译并且测试运行良好。当我排除测试项目但包含静态变量时,该解决方案也可以编译、链接和运行良好,所以我假设它与我的设置有关。我一直在修补它一段时间,对它可能是什么感到困惑。我错过了什么明显的东西吗?

【问题讨论】:

  • 我能想到的唯一问题是Debug.cpp 没有与 B.cpp 所在的“单独的测试项目”链接在一起。 (我相信您在提问之前已经尝试摆脱 typedef std::shared_ptr&lt;Debug&gt; DebugPtr; 并将所有对 DebugPtr 的引用替换为 std::shared_ptr&lt;Debug&gt;,对吧?)
  • @MikeNakis 是的,这是我尝试过的第一件事,因为我以前遇到过这种情况。不过,这并没有改变结果。我将在我的示例中去掉 typedef 以避免这种混淆。

标签: c++ visual-studio-2013 boost-test


【解决方案1】:

仍然不确定为什么测试项目没有捕获 .cpp 文件中静态变量的定义,但我找到了一种解决方法,虽然它有点 hacky。

在我的测试项目中,在包含'main'定义的文件中,我将Debug的.cpp文件添加为#include(其中定义了静态变量)。像这样:

#define BOOST_TEST_DYN_LINK

#ifndef BOOST_TEST_MODULE ProjectTesting
#define BOOST_TEST_MODULE ProjectTesting
#endif
#ifndef BOOST_TEST_MAIN
#define BOOST_TEST_MAIN
#endif

#include <boost\test\unit_test.hpp>
#include "<path-to-folder>/Debug.cpp"

这可能不是最好的解决方案,但它最终可以正确编译和运行。如果有人能想到一个不那么老套的解决方法,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 2011-03-10
    • 2021-11-28
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多