0

There is a RPC framework, using hessian as out default serialization. Then, some clients need protobuf. In order to be compatible with those people who do not have protobuf installed, we put all protobuf supports into a single file, and compile it conditionally according to the current enviroment(have pb or not)
The framework has a serial of data types(Long, String, Map, etc), each of them has a serializer seperately, we use a static struct to register these functions, it looks like:

/*file register.cc */

In the protobuf support file, we do the similar things:

/* pb_support.cc */

the two files exit in different directories:
In gcc 4.1.2 with Redhat5.6, it works well. In gcc 4.8 with Ubuntu 13.04, When protobuf is in, the pb_object_install always excutes first, but the result of is zero, that means the result of pb registeration has been wiped out, so protobuf protocol is useless.
Why is that? and is there any substitution to accomplish the same function?

nzomkxia
  • 1,219
  • 4
  • 16
  • 35
  • 2
    Static initialization order is unspecified. Two file-static objects in two different files simply cannot refer to one another. You should make `serializer_registry` function-static instead of file-static, to guarantee it is initialized on first use. Or make it a proper singleton. – n. m. could be an AI Jul 23 '14 at 09:27

1 Answers1

3

The initialization of variables in the global namespace is in the order of declaration in a single translation unit. However, the order of initialization between translation units is not specified.

That means if you have two source files, you can't say which files variables will be initialized first. That will of course cause problems if a variable in one source file depends on a variable in another source file being initialized first.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • if the pb part excuted first, why the array serializer_registry is still empty when it comes to the hessian part? are the two initialization excuted one by one? – nzomkxia Jul 23 '14 at 09:23
  • 2
    The program has UB. Fix it, and don't ask why UB is manifested in this particular way. Such questions are unproductive. (Though it's easy to see that the pb part illegally writes to the registry before its constructor is called, then the constructor is called, wiping whatever was written). – n. m. could be an AI Jul 23 '14 at 09:37
  • @n.m. thanks, I'm planing to change the whole logic about this. just curious, what do u mean by "registry before its constructor is called", from my perspective, regist_serializer is call inside the pb's constructor. – nzomkxia Jul 24 '14 at 01:27
  • I mean before the constructor of registry is called. – n. m. could be an AI Jul 24 '14 at 02:50