[CMake] Newbie question: Static linking

Michael Wild themiwi at gmail.com
Mon May 23 05:18:48 EDT 2011


On 05/23/2011 10:23 AM, Hendrik Sattler wrote:
> Zitat von Sanatan Rai <sanatan at gmail.com>:
>> 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.
> 
> Then you don't understand the implications of static libraries, yet.
> Use the following from "man ld":
>  --whole-archive
>        For    each  archive  mentioned  on  the  command  line   after  
> the
>        --whole-archive option, include every object file in the archive in
>        the link, rather than searching the archive for the required object
>        files.  This is normally used to turn an archive file into a shared
>        library, forcing every object  to  be  included  in    the 
> resulting
>        shared library.  This option may be used more than once.
> 
>        Two    notes when using this option from gcc: First, gcc doesn't
> know
>        about this option, so you have to use -Wl,-whole-archive.   Second,
>        don't  forget  to  use  -Wl,-no-whole-archive  after     your 
> list of
>        archives, because gcc will add its own list    of  archives  to 
> your
>        link and you may not want this flag to affect those as well.
> 
> HS

But this will only work when using GNU ld (or compatible). AFAIK the
linker on APPLE uses a different option, and MSVC doesn't have an
equivalent at all (you can only specify individual symbols that should
be linked forcibly).

The real solution is to ditch this whole idea of global, static
initialization objects. It's usually a very bad solution, leading to all
kinds of non-deterministic behavior. You'll be much better off with an
explicit registration scheme.

My 2c.

Michael


More information about the CMake mailing list