我正在编写测试代码,其中有一个TestUtil.h
,它定义了两个常量和一些函数。我已经将此头文件实现为TestUtil.cpp
,并且在其中我正在编写实际测试的第三个文件ActualTests.cpp
。 TestUtil.h
和TestUtil.cpp
只是用于编写简洁测试的帮助文件。
我有嵌套的名称空间,TestUtil.h
看起来像这样:
namespace SNMPSubAgentTesting {
namespace MibDataReaderTesting {
const wchar_t* TEST_MUTEX_NAME = L"TestMutex";
const wchar_t* TEST_MEMORY_NAME = L"TestMemory";
//some functions
}
}
在实现TestUtil.cpp
中,我包括以上头文件并给出实现:
#include "TestUtil.h"
namespace SNMPSubAgentTesting {
namespace MibDataReaderTesting {
//implementations
}
}
在第三个文件ActualTests.cpp
中,我再次包含TestUtil.h
以使用util函数:
#include "TestUtil.h"
namespace SNMPSubAgentTesting {
namespace MibDataReaderTesting {
//Test class and tests
}
}
编译器给出了一个链接错误,并说const
中的两个TestUtil.h
变量已在TestUtil.cpp
中定义,因此ActualTests.cpp
无法编译。由于const
变量是内部链接的,我们可以在多个文件中包含包含const
变量的标头,而不会链接错误,为什么在我的情况下它不链接?是因为嵌套的名称空间吗?
编辑:我正在使用Microsoft单元测试框架进行测试。const变量位于MibDataReaderTesting命名空间中,而不位于全局命名空间中。
我的源代码中有头文件,这些头文件包含在多个文件中,并且其中包含const变量。在这种情况下没有错误,但在测试情况下却给出了错误。黑白源和测试代码的唯一区别是测试框架和嵌套名称空间
如this internal linkage reference const
中限定的名称具有内部链接。
问题是您的名字是not const
限定的。 const
用于指针所指向的数据,而不用于变量本身。
您需要在正确的位置添加const
:
const wchar_t* const TEST_MUTEX_NAME = L"TestMutex";
// ^^^^^
// Make TEST_MUTEX_NAME itself constant