0

I have the following cpp code taken from geeksforgeeks web:

#include <iostream>
class Geek{

public:
    static int i;

    void myFunction(){
            
        (Geek::i)++;
        std::cout << "Hello Geek!!!" << Geek::i << std::endl;
    }
};
 int Geek::i=0;
  int main()
{
// Creating an object
Geek t; 

// Calling function
t.myFunction();  

return 0;
}

extern "C" {
Geek* Geek_new(){ return new Geek(); }
void Geek_myFunction(Geek* geek){ geek -> myFunction(); }
}

i've compiled it and create so file using the following commands: g++ -c -fPIC foo.cpp -o foo.o g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o

and called the so file from the python part:

# import the module
from ctypes import cdll

# load the library
lib = cdll.LoadLibrary('./libfoo.so')

# create a Geek class
class Geek(object):

# constructor
def __init__(self):

    # attribute
    self.obj = lib.Geek_new()
    self.obj2 = lib.Geek_new()

# define method
def myFunction(self):
    lib.Geek_myFunction(self.obj)
    lib.Geek_myFunction(self.obj2)

# create a Geek class object
f = Geek()

# object method calling
f.myFunction()
f.myFunction()

when i run this code i'm getting the following error: ./libfoo.so: undefined symbol: _ZN4Geek1iE

if i place the static variable inside my function and compile it, it works fine, but i need the variable to be a static member of the class.

what needs to be done to make it work?

UPDATE i've update the code according to tevemadar, and it worked. i needed to initialize GEEK::i outside the class

Joe
  • 171
  • 2
  • 19
  • 1
    I don't see the `int Geek::i;` line. My C++ is a bit aged, but it still seems to be necessary: https://en.cppreference.com/w/cpp/language/static – tevemadar Feb 23 '22 at 09:16
  • The elusive part here is that you are compiling a *library*, which doesn't have to be complete in itself, missing parts could come from other compilation units. Just they didn't, and that's how it becomes a runtime error instead. – tevemadar Feb 23 '22 at 09:21
  • thank you all for replying, i've updated my question accordng to tevemadar answer and it worked!!! – Joe Feb 23 '22 at 09:36

1 Answers1

0

Thanks to tevemadar for his answer. we as GEEK::i and not just i in the class. and initialize it outside the class

int GEEK::i = 0;

updated code can be seen in the question

Joe
  • 171
  • 2
  • 19