Hi Corona688,
I made a simple example and it works. When you create a library, you do not need definitions that are also in the main app since they can be resolved when the object is loaded.
Main App: BaseClass.h, BaseClass.cpp, OtherClass.h, OtherClass.cpp, main.cpp
Shared Library: ChildClass.h, ChildClass.cpp, BaseClass.h, OtherClass.h
Note: I included OtherClass to show that the definition did not need to exist in the shared library.
BaseClass.h
#ifndef BASE_CLASS_H
#define BASE_CLASS_H
#include <string>
#include "OtherClass.h"
using std::string;
class BaseClass
{
public:
static int val;
BaseClass();
virtual ~BaseClass();
virtual string getString() = 0;
private:
};
#endif
BaseClass.cpp
#include "BaseClass.h"
int BaseClass::val = 5;
BaseClass::BaseClass()
{
}
BaseClass::~BaseClass()
{
}
ChildClass.h
#ifndef CHILD_CLASS_H
#define CHILD_CLASS_H
#include "BaseClass.h"
class ChildClass : public BaseClass
{
public:
ChildClass();
string getString();
};
extern "C" BaseClass * create();
#endif
ChildClass.cpp
#include "ChildClass.h"
ChildClass::ChildClass(): BaseClass()
{
OtherClass oc(4);
oc.getValue();
}
string ChildClass::getString()
{
return "child class";
}
BaseClass * create()
{
return new ChildClass();
}
OtherClass.h
#ifndef OTHER_CLASS_H
#define OTHER_CLASS_H
class OtherClass
{
public:
OtherClass(int value);
int getValue();
private:
int value;
};
#endif
OtherClass.cpp
#include "OtherClass.h"
OtherClass::OtherClass(int value)
{
this->value = value;
}
int OtherClass::getValue()
{
return value;
}
main.cpp
#include "BaseClass.h"
#include <iostream>
#include <dlfcn.h>
using std::cout;
using std::endl;
int main()
{
typedef BaseClass * (*CreateFunc)();
void *handle = dlopen("./libsltest.so.1.0", RTLD_NOW);
if (handle)
{
cout << "loaded library" << endl;
CreateFunc cf = (CreateFunc)dlsym(handle, "create");
if (cf)
{
cout << "loaded create function" << endl;
BaseClass *b = cf();
cout << b->getString() << endl;
dlclose(handle);
cout << BaseClass::val << endl;
cout << b->val << endl;
}
else
{
cout << "could not load create function" << endl;
}
}
else
{
cout << "could not load library" << endl;
}
return 0;
}
The static values are the same, as expected.
In the project where I'm getting unresolved errors, I'm using Qt to make the shared library. The problem could be there. I'll post again if I have any leads.
Thanks for your help,
-- Derek