This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: External variables in shared library constructor code
- From: Eljay Love-Jensen <eljay at adobe dot com>
- To: smokyboy <smokyboy0 at lycos dot com>, GCC-help <gcc-help at gcc dot gnu dot org>
- Date: Thu, 14 Aug 2008 06:48:19 -0500
- Subject: 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