https://sourceware.org/bugzilla/show_bug.cgi?id=20152

--- Comment #2 from Dave Malcolm <dmalcolm at redhat dot com> ---
(In reply to Nick Clifton from comment #1)
> Hi Dave,
> 
> > I noticed when developing a patch for GCC that C++ objects with global
> > constructors are sometimes discarded if linked via a .a archive.
> 
> Why is this surprising ?  The point of an archive is that contents are only
> extracted from it if they are needed.  If nothing in the main program
> references the global object in the library then it is not included in the
> link and its constructor is never run.

The word "object" is rather overloaded in this discussion.

If foo.o contains a C++ object "f" with a global constructor and "f" is not
used, then:

  * if foo.o is linked directly into an executable, f's ctor is run before
"main".
  * if foo.o is linked into a .a and then that .a is linked into an executable,
f's ctor may or may not be run before "main".  The constructor is only run if
there's at least one symbol in foo.o that's referenced by the main program.

Note that although the C++ object f isn't used, f's ctor may have interesting
side-effects that need to happen; the parameters may reference things that need
to be linked (in my case I was using it to register unit testing functions with
a test runner).

I don't know if this behavior is a bug, but this is sufficiently surprising to
me that I wanted to capture it somewhere with a URL; it seems like a "gotcha"
to me  (it took me a couple of days of stepping through the link of gcc to
track down).

Hope the above makes sense.

-- 
You are receiving this mail because:
You are on the CC list for the bug.
_______________________________________________
bug-binutils mailing list
bug-binutils@gnu.org
https://lists.gnu.org/mailman/listinfo/bug-binutils

Reply via email to