Search code examples
c++googletest

Test project has problems accessing a private static method, even though I never directly call it


I am trying to add some missing skills to my repertoire, one of which is setting up a proper parallel test project.

I have a simple setup in one project (EffCPP) to experiment with some C++ concepts and I am trying to set up a Google Test project (Test) in another one that can access all relevant files and test them.

Unfortunately, after setting up the testing project successfully, I started having problems constructing data from the EffCPP project in the Test one.

Specifically, a linker error that says my test project cannot link a private static method that the public constructor accesses.

I am sure I am missing something about the compilation process here but the solution seems quite non obvious and the query itself is hard to google.

I have a github repository of all this located here : https://github.com/Vidrohi/EffectiveCPP.git

It was suggested that I try to create a simple example of the situation in the question. What follows is my attempt at explaining the same :

///////////////////////// EffCPP ////////////////////////////////


/////////////////////////  ClassToBeTested.h ////////////////////////////////


class ClassToBeTested
{
private:
    unsigned int m_id;

    static unsigned int s_currentId;
    static unsigned int GetNextId();

public:

    ClassToBeTested():m_id(GetNextId())
    {}  
}

/////////////////////////  ClassToBeTested.cpp ////////////////////////////////

#include "ClassToBeTested.h"

unsigned int Performance::NonPOD::s_currentId = 0;

unsigned int Performance::NonPOD::GetNextId()
{
    return ++s_currentId;
}

///////////////////////// TestProject ////////////////////////////////

///////////////////////// Tests.cpp /////////////////////////

#include "gtest/gtest.h"
#include "../EffCPP/Chapter6/ClassToBeTested.h" // Just the path where that header is located really

std::string name("NAME");
TEST(name, name) {
    EXPECT_EQ(1, 1); // Just to make sure the test framework is running correctly

    ClassToBeTested cp;
}

Edit 2 : Interestingly I found another question which talks about pretty much the same issue link but this just suggests that I set up a third project to build as a lib and then link that static lib in. Is that the only way to do this ?


Solution

  • One possible solution to this problem is to not create an executable from the EffCPP project but instead create a static lib. This static lib can then easily be provided to the test project which can then link it and run itself as an exe.

    Another possible solution can be found in this question but that requires creating a third project.

    I am still looking for a way to be able to use just two projects and build both as .exe