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