This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: External variables in shared library constructor code


Hi smokyboy,

There are no guarantees as to the order of initialization in the C/C++
standards.

Some compilers provide initialization ordering extensions, but those are
usually within a package (such as a DLL), and not across packages (DLLs).

One solution is to hide the external variable within a global function call:

// C++
extern int& GlobalIntValue();

// C
extern int* GlobalIntValue();

That way, the function call can guarantee the variable is initialized on
demand, and that the global variable is only initialized once.

The routine will look like this, in C++:

int& GlobalIntValue()
{
  static int foo = 77;
  return foo;
}

And in C:

int* GlobalIntValue()
{
  static int foo = 77;
  return &foo;
}

HTH,
--Eljay


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]