2

I have defined a static struct in a class. but it is resulting error as Error

error LNK1120: 1 unresolved externals

my header file

class CornerCapturer{
    static struct configValues
    {
        int block;
        int k_size;
        int thre;
        double k;
        configValues() :block(2), k_size(3), thre(200), k(0.04){}
    }configuration;
public:
    void captureCorners(Mat frame);
}

my cpp file

void CornerCapturer::captureCorners(Mat frame){

    int y= CornerCapturer::configuration.thre;
}

please help me

Mat
  • 202,337
  • 40
  • 393
  • 406

2 Answers2

5

Add this into your cpp file; to instantiate the static structure:

CornerCapturer::configValues CornerCapturer::configuration;

and dont forget the ; after the enclosing } of your class.

A.S.H
  • 29,101
  • 5
  • 23
  • 50
  • 1
    Thank you very much for helping me.I just missed it. –  Dec 30 '16 at 05:59
  • This works great when linking only a single source file that uses the static member class, but when I try to reference the static member class from a second source file by adding the suggested line to the second file, I get a multiple definitions error. – Jim Fell Mar 25 '20 at 15:00
0

Static member variables need to be made public. The way you currently have it setup implicitly makes the struct private. I ran a few tests and what ASH says is correct you have to instantiate the structure in the global scope but you can't do that with a private member. Personally, I get the scoping error:

'configuration' is a private member of 'Someclass'

Only after I make the struct public: did it compile without error.

#include <iostream>

class Someclass 
{
public:       
    static struct info 
    {
        int a;
        int b;
        int c;
        info() : a(0), b(0), c(0){}

    } configuration;

    void captureCorners(int frame);
};

struct Someclass::info Someclass::configuration;

void Someclass::captureCorners(int frame) 
{
    configuration.c = frame;
}

int main ()
{
    Someclass firstclass;
    Someclass secondclass;

    Someclass::configuration.a = 10;
    firstclass.configuration.b = 8;
    secondclass.configuration.c = 3;

    using namespace std;


    cout << "First Class a = " << firstclass.configuration.a << "\n";
    cout << "First Class b = " << firstclass.configuration.b << "\n";
    cout << "First Class c = " << firstclass.configuration.c << "\n";

    cout << "Second Class a = " << secondclass.configuration.a << "\n";
    cout << "Second Class b = " << secondclass.configuration.b << "\n";
    cout << "Second Class c = " << secondclass.configuration.c << "\n";

    cout << "Everyclass a = " << Someclass::configuration.a << "\n";
    cout << "Everyclass b = " << Someclass::configuration.b << "\n";
    cout << "Everyclass c = " << Someclass::configuration.c << "\n";

}
epsilonv
  • 1
  • 3