Question

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() {}
};
Was it helpful?

Solution

You only declared field eventXml. You need to define it somewhere. In some .cpp file you must put line like

xml ParsingEventsTest::eventXml;

EDIT
As for the reason why it is needed: declaration of static member in class can not define it. If it did, every translation unit which includes class definition would define it. But each program needs exactly one definition, so you have to choose place where member is defined outside the class definition (usually in some .cpp file. Best is the one with member functions definition). And the syntax looks like above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top