Friday, September 18, 2015

c++ - Variables in static library are never initialized. Why?



I have a bunch of variables that should be initialized then my game launches, but must of them are never initialized.


Here is an example of the code:


MyClass.h


class MyClass : public BaseObject {
DECLARE_CLASS_RTTI(MyClass, BaseObject);
...
};


MyClass.cpp


REGISTER_CLASS(MyClass)

Where REGISTER_CLASS is a macro defined as follow


#define REGISTER_CLASS(className)\
class __registryItem##className : public __registryItemBase {\
virtual className* Alloc(){ return NEW className(); }\
virtual BaseObject::RTTI& GetRTTI(){ return className::RTTI; }\
}\
\

const __registryItem##className __registeredItem##className(#className);

and __registryItemBase looks like this:


class __registryItemBase {
__registryItemBase(const _string name):mName(name){ ClassRegistry::Register(this); }
const _string mName;
virtual BaseObject* Alloc() = 0;
virtual BaseObject::RTTI& GetRTTI() = 0;
}


Now the code is similar to what I currently have and what I have works flawlessly, all the registered classes are registered to a ClassManager before main(...) is called. I'm able to instantiate and configure components from scripts and auto-register them to the right system etc...


The problem arrises when I create a static library (currently for the iPhone, but I fear it will happen with android as well). In that case the code in the .cpp files is never registered.


Why is the resulting code not executed when it is in the library while the same code in the program's binary is always executed?




Bonus questions:


For this to work in the static library, what should I do?



  • Is there something I am missing?

  • Do I need to pass a flag when building the lib?

  • Should I create another structure and init all the __registeredItem##className using that structure?




Answer



This answer actually fixes the issue:




Use the -all_load linker option to load all members of static libraries. Or for a specific library, use -force_load path_to_archive.


In Xcode, you'll want to add these options under "Other Linker Flags" for your executable (not your static library).




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...