amitfr
amitfr

Reputation: 1093

static statement at the head of .cpp file not called

I have a class file in the common foundations code of the company called Receiver.

One of the first lines of the cpp file of this class (after the #include lines) says:

static const bool res = ReceiverFactory::registerCreator(Receiver::getProjectReceiverName(), Receiver::create );

On one of the application that use this code, I can see that this line runs when app is starting.

On a similar application this is not the case. This line does not run at all. I need to explicitly construct an object of that class to get this line to execute.

Is that a VS solution/project configuration issue? Any other ideas?

Upvotes: 0

Views: 91

Answers (1)

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95499

It sounds like the linker is eliding or deferring the evaluation of this statement due to the lack of references to it. This problem has already been solved before, though, so you may want to take advantage of existing solutions. One solution is to have a list of initialization routines that are explicitly iterated through in the main() method on initialization. This is more or less the approach taken by Google's REGISTER_MODULE_INITIALIZER function that is in the Chromium source code:

http://src.chromium.org/svn/releases/3.0.190.2/src/third_party/cld/base/googleinit.h

With that code in particular, it's possible to do:

REGISTER_MODULE_INITIALIZER(register_creator, {
    ReceiverFactory::registerCreator(
         Receiver::getProjectReceiverName(), &Receiver::create);
});

And then explicitly initialize this (and other modules) in main, with:

int main(int argc, char* argv[]) {
  RUN_MODULE_INITIALIZERS();
  // ...
}

There are other ways to do this kind of static initialization, as well, such as __attribute__((constructor)) (though that is non-standard) or creating a non-POD object statically whose constructor function does the intialization that you want, for example:

namespace initialization {
namespace {

  class DoStaticInitialization {
    public:
      DoStaticInitialization() {
          ReceiverFactory::registerCreator(
             Receiver::getProjectReceiverName(), &Receiver::create);
      }
  };
  DoStaticInitialization initializer_instance_;

}
}

Upvotes: 1

Related Questions