单元测试dll链接不一致导致编译错误

Unit testing Inconsistent dll linkage leads to compilation error

C++ 新手,正在尝试测试一个 dll,但不断得到

warning C4273: 'CRootFinder::SquareRoot' : inconsistent dll linkage 

RootFinder.h

#ifdef MY_EXPORTS
#define API _declspec(dllexport)
#else
#define API _declspec(dllimport)
#endif

class API CRootFinder {
public:
    CRootFinder(void);
    double SquareRoot(double v);
};

RootFinder.cpp

#include "stdafx.h"
#include "RootFinder.h"

double CRootFinder::SquareRoot(double v)
{
    return 0.0;
}

构建但收到上面的警告。

在单元测试项目中添加了对 dll 的引用

unittest1.cpp

#include "stdafx.h"
#include "CppUnitTest.h"
#include "../c source/RootFinder.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace Tests
{       
    TEST_CLASS(UnitTest1)
    {
    public:

        TEST_METHOD(TestMethod1)
        {
            CRootFinder rooter;
            Assert::AreEqual(
                // Expected value:
                0.0,
                // Actual value:
                rooter.SquareRoot(0.0),
                // Tolerance:
                0.01,
                // Message:
                L"Basic test failed",
                // Line number - used if there is no PDB file:
                LINE_INFO());
        }

    };
}

不会构建

Error 2 error LNK2019: unresolved external symbol "__declspec(dllimport) public: __thiscall CRootFinder::CRootFinder(void)" (__imp_??0CRootFinder@@QAE@XZ) referenced in function "public: void __thiscall Tests::UnitTest1::TestMethod1(void)" (?TestMethod1@UnitTest1@Tests@@QAEXXZ)

使用 MY_EXPORTS 预处理器 marco 编译 dll。在没有 MY_EXPORTS 定义宏的情况下添加在测试中使用它。

在 Visual Studio 中,您可以这样做:Project right click->Propertis->C/C++->Preprocessor->Preprocessor Definitions,只需将 MY_EXPORTS 添加到 dll 项目的列表中,并在没有 MY_EXPORTS 的测试项目列表中保留该列表。

并且您需要在 RootFinder.cpp.

中定义构造函数 CRootFinder()