Search code examples
c++factory-patternstatic-linking

Static objects are not being linked in a static lib in VC 2010. How do I force a link?


I have a static factory that relies on a static member of itself to register the class into the factory system.

class Foo_A_Maker : public FooFactory<Foo, const std::string &>
{
private:
    // Register this as a type using a static instance of itself.
    // This is really the only time it is created. That's why the
    // constructor is private.
    Foo_A_Maker() : FooFactory("Foo_A") {}
    static const Foo_A_Maker registerThis;

public:
    virtual std::shared_ptr<Foo> MakeProduct(const std::string& params) const;
};

This has worked for years in all my projects, but now I have added it to a static library. In the static library, the ctor is never called and the object never registers. If I put this code in the exe project it works again. I have determined that this is not linking by introducing a link time error.

Am I missing something? Can I force a link? And if I use this across compilation boundaries can the EXE project add its own factories?

Thanks all.


Solution

  • This is how libs are supposed to work - the linker only takes the symbols it needs (referenced from the outside). The correct way of solving this is to provide an init function.

    For Visual Studio you can find the exact symbol name that you need, and pass /INCLUDE as a command-line option to the linker. You can try with /OPT:NOREF - it sounds like it could work, but haven't tested it.