5

I am writing a testcase that will have a SetUpTestCase() method that will allocate a shared resource although I am receiving undefined reference linker errors.

class ParsingEventsTest: public ::testing::Test {
    protected:

        static xml eventXml;

        static void SetUpTestCase() {
            ManagedObjectManagerSingleton::GET_SINGLETON().initializeTestEnvironment(PATH_TO_FILE);
            eventXml= *ManagerSingleton::GET_SINGLETON().parse(PATH_TO_INPUT_FILES);
        }

        virtual void SetUp() {}
        virtual void TearDown() {}
};

This would cause:

../test/ParsingEventsTest.o: In function `ParsingEventsTest::SetUpTestCase()':
ParsingEventsTest.cpp:(.text._ZN17ParsingEventsTest13SetUpTestCaseEv[ParsingEventsTest::SetUpTestCase()]+0xa1): undefined reference to `ParsingEventsTest::eventXml'
ParsingEventsTest.cpp:(.text._ZN17ParsingEventsTest13SetUpTestCaseEv[ParsingEventsTest::SetUpTestCase()]+0xb0): undefined reference to `ParsingEventsTest::eventXml'
ParsingEventsTest.cpp:(.text._ZN17ParsingEventsTest13SetUpTestCaseEv[ParsingEventsTest::SetUpTestCase()]+0xbd): undefined reference to `ParsingEventsTest::eventXml'
ParsingEventsTest.cpp:(.text._ZN17ParsingEventsTest13SetUpTestCaseEv[ParsingEventsTest::SetUpTestCase()]+0xc2): undefined reference to `ParsingEventsTest::eventXml'
ParsingEventsTest.cpp:(.text._ZN17ParsingEventsTest13SetUpTestCaseEv[ParsingEventsTest::SetUpTestCase()]+0xce): undefined reference to `ParsingEventsTest::eventXml'
../test/ParsingEventsTest.o:ParsingEventsTest.cpp:(.text._ZN17ParsingEventsTest13SetUpTestCaseEv[ParsingEventsTest::SetUpTestCase()]+0xdd): more undefined references to `ParsingEventsTest::eventXml' follow
collect2: ld returned 1 exit status

EDIT:

This also works for very simple e.g. int allocation

class ParsingEventsTest: public ::testing::Test {
    protected:

        static int *x;

        static void SetUpTestCase() {
            x = new int [30];
        }

        static void TearDownTestCase() {
            delete [] x;
        }

        virtual void SetUp() {}
        virtual void TearDown() {}
};
4

1 回答 1

10

你只声明了 field eventXml。你需要在某个地方定义它。在某些 .cpp 文件中,您必须像这样放置行

xml ParsingEventsTest::eventXml;

编辑
至于需要它的原因:类中静态成员的声明不能定义它。如果是这样,每个包含类定义的翻译单元都会定义它。但是每个程序都需要一个定义,因此您必须选择在类定义之外定义成员的位置(通常在某些 .cpp 文件中。最好是具有成员函数定义的那个)。语法如上所示。

于 2013-06-28T08:22:54.917 回答