[CMake] Newbie question: Static linking

Sanatan Rai sanatan at gmail.com
Mon May 23 03:12:25 EDT 2011


On 23 May 2011 00:53, Hendrik Sattler <post at hendrik-sattler.de> wrote:
> Am Montag, 23. Mai 2011, 01:36:14 schrieb Sanatan Rai:
>> After cmake, and make all, the libraries build as static archives, ie I get
>> liblib1.a, liblib2.a, libhelper1.a, libhelper2.a and executable myProj in
>> the appropriate locations. However, the executable myProj does not appear
>> to have linked statically to libhelper1.a and libhelper2.a. These
>> libraries contain global initialisers for certain objects: which doesn't
>> happen when I run the executable.
>
> Most likely, the linker just drops those "global initialisers" when linking
> statically.  See the linker options in "man ld" to prevent that or give the
> library an initialisation method.

   I don't understand: so why does it work at all? I guess what I
don't understand is that
I don't see symbols from helper1 and helper2 in the final executable,
when I build them
as separate libraries, but I do when I express the dependencies thus:

  add_executable(myTarget target.cpp helpers/helper1.cpp helpers/helper2.cpp)

The `global initialisation' stuff is just the following pattern:

namespace {
  helper1 *helper1Creator()
  {
    return (new helper1());
  }
  const bool helper1Registered = factory::instance().registerhelper
    ("helper1", helper1Creator);
}

So when I put the helpers in a separate library, these lines are not
called: which
suggests that the library was not loaded in memory. On the other hand,
when I build
them with the executable, the lines are called and everything works as expected.
I am not sure what else I can tell the linker. The libraries are
static so should be linked
statically. As far as I can tell, somehow the two helper libraries are
not being linked
at all.

Sorry, but I am quite confused.

--Sanatan


More information about the CMake mailing list