Take a look at my source. I have 3 source files here that get compiled as object files and then all linked together. Explaination of my problem follows source.
script.cpp
Code:
list<LS_RegisterFunction *> LS_RegisterFunction::gs_RegisteredFuncs;
script.h
Code:
class LS_RegisterFunction
{
public:
static list<LS_RegisterFunction *> gs_RegisteredFuncs;
string Name;
lua_CFunction FuncPtr;
LS_RegisterFunction(char *cpName, lua_CFunction Ptr)
{
this->Name = cpName;
this->FuncPtr = Ptr;
LS_RegisterFunction::gs_RegisteredFuncs.push_back(this);
}
~LS_RegisterFunction()
{
this->gs_RegisteredFuncs.remove(this);
}
};
test.cpp
Code:
class Test
{
public:
int iTestInt;
};
int MyFunc(lua_State *LuaState);
LS_RegisterFunction TestPtr("MyFunc", MyFunc);
int MyFunc(lua_State *LuaState)
{
}
main.cpp
Code:
int main(etc...)
{
etc...
/* Register all functions to Lua in gs_RegisteredFuncs */
etc...
}
I have a macro called LUA_REGISTERED_FUNCTION, like so:
Code:
#define LUA_REGISTERED_FUNCTION(Name) \
int LuaScriptFunction_ ## Name (lua_State *LuaState); \
LS_RegisterFunction LuaScriptFunctionPtr_ ## Name ( #Name, LuaScriptFunction_ ## Name); \
int LuaScriptFunction_ ## Name (lua_State *LuaState)
This way, I can simply create a function in Lua like this:
Code:
LUA_REGISTERED_FUNCTION(HelloWorld)
{
lua_pushstring("Hello world!");
return 1;
}
All that is to say:
If I compile and link the 3 object files above (script.o, test.o, main.o) then it causes a Segmentation fault
IF I link in this order: main.o, script.o, test.o (e.g. g++ -o mytest main.o script.o test.o -llua -llualib)
However, if I link the object files in the order: main.o, test.o, script.o then the Segmentation fault goes away, and the program runs fine. Why is this? I am just going to link in the right order for now, but I would like to now why, and possibly how to work around it.
By the way, I did some tests, and gs_RegisteredFuncs doesn't exists in the LS_RegisterFunction contructer if I link the object files as in example 1 (main, script, test). This tells me that the global variable isn't being created before the constructor gets called. But I thought it wasn't possible for a class to call it's constructor while static members weren't created yet?