public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* External variables in shared library constructor code
@ 2008-08-14  7:16 smokyboy
  2008-08-14 12:21 ` Eljay Love-Jensen
  0 siblings, 1 reply; 2+ messages in thread
From: smokyboy @ 2008-08-14  7:16 UTC (permalink / raw)
  To: gcc-help


Hi,

I have a problem using external variables in the constructor code of my
shared library. The constructor code is an init() function labeled by gcc
__attribute__((constructor)). In that function I make a reference to an
extern variable X provided by the driving app. The problem is that X is not
yet initialized at the moment init() is invoked, which is before main() is
entered.
A solution might be to introduce a init flag and move the initialization
code to some other exported function, but this is not really elegant. I will
appreciate any alternative suggestion.
-- 
View this message in context: http://www.nabble.com/External-variables-in-shared-library-constructor-code-tp18976389p18976389.html
Sent from the gcc - Help mailing list archive at Nabble.com.

^ permalink raw reply	[flat|nested] 2+ messages in thread

* Re: External variables in shared library constructor code
  2008-08-14  7:16 External variables in shared library constructor code smokyboy
@ 2008-08-14 12:21 ` Eljay Love-Jensen
  0 siblings, 0 replies; 2+ messages in thread
From: Eljay Love-Jensen @ 2008-08-14 12:21 UTC (permalink / raw)
  To: smokyboy, GCC-help

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

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2008-08-14 11:49 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2008-08-14  7:16 External variables in shared library constructor code smokyboy
2008-08-14 12:21 ` Eljay Love-Jensen

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).