kiriloff
kiriloff

Reputation: 26333

C++ GoogleTest - static member and linker error LNK 2001

I have this code sample, defining a fixture in a googletest.

#include "solver.h"

#include <math.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;


class UnitTest_solver : public ::testing::Test
{
protected:

    static void SetUpTestCase()
    {
        // setup table with data
        m_col = 2; 
        m_test_data = new double*[m_row];
        for(int i = 0 ; i < m_col ; i++)
            m_test_data[i] = new double[m_row];

        ifstream data_x;
        data_x.open("exponential2X.txt");

        // etc... : i setup table m_test_data in a few more lines
}



static void TearDownTestCase()
{
    for(int i = 0 ; i < m_row ; i++)
        delete[] m_test_data[i];
    delete[] m_test_data;
}



 static double chi_sqr(double* x, double(*func)(double*, double*, int))
 {
    if(ncol < 2)
        return;

    double fx = 0;

    double * row_i = new double[ncol - 1];

    for(int i = 0 ; i < nrow ; i++)
    {
        for(int j = 0 ; j < ncol - 1 ; j++)
            row_i[j] = data[i][j];

        fx += pow(data[i][0] - (*func)(x, row_i, ncol - 1), 2.0); 
    }

    return fx;
 }


 static double func_1(double* x, double* dbl, int nb_param)
 {
    if(nb_param != 2)
         return 0;

    return x[0] * exp(-1 * x[1] * dbl[0]);
 }


 static double warpPt2apply_func(double * parameters, int ncol, void * userinfo, int nb_p)
 {
      return  chi_sqr(parameters, (ncol - 1), (*func_1));
 }

  static double** m_test_data;
  static int m_col, m_row;

};


TEST_F(UnitTest_solver, testFunc1)
{
    Solver* solver = new Solver();
    solver->set_pointer(warpPt2apply_func, (void*)NULL);
}

i have LNK 2001 error, problably related to the use of static data member, pointing to members m_test_data, m_col, m_row. is it because SetUpTestCase() method is called for each new test in the test suite at the beginning, whereas static member should be initialized once and for all.

Any idea?

Thanks

Upvotes: 0

Views: 977

Answers (1)

ForEveR
ForEveR

Reputation: 55887

  static double** m_test_data;
  static int m_col, m_row;

Initialize outside of class in enclosing namespace

  double** UnitTest_solver::m_test_data = 0;
  int UnitTest_solver::m_col = 0;
  int UnitTest_solver::m_row = 0;

Upvotes: 2

Related Questions