Unittesting in static libraries

Steven Schveighoffer schveiguy at yahoo.com
Mon Sep 19 03:52:11 PDT 2011


On Sat, 17 Sep 2011 11:11:35 -0400, Jérôme M. Berger <jeberger at free.fr>  
wrote:

> Steven Schveighoffer wrote:
>> On Fri, 16 Sep 2011 15:14:50 -0400, Jérôme M. Berger <jeberger at free.fr>
>> wrote:
>>
>>> Andrej Mitrovic wrote:
>>>> I'd like to turn some attention to unittests, which don't seem to work
>>>> with static libraries. Consider:
>>>>
>>>> .\main.d:
>>>> import mylib.test;
>>>> void main()
>>>> {
>>>>     auto x = foo();
>>>> }
>>>>
>>>> .\mylib\test.d
>>>> module mylib.test;
>>>> int foo() { return 1; }
>>>> unittest { assert(0); }
>>>>
>>>> $ dmd -unittest main.d mylib\test.d && main.exe
>>>> core.exception.AssertError at mylib.test(5): unittest failure
>>>>
> [snip]
>>>
>>>     I think that it is not a bug, it is a feature (sort of). Could you
>>> look at the assembly generated for your main.d file? My guess is
>>> that it does not reference foo at all, either because the call to
>>> foo was inlined or because it was discarded (since you do not use x
>>> after initializing it).
>>>
>>>     The reason it works with the first form is that all object files
>>> that are specifically put on the command line are included in the
>>> executable when linking even if they are not used.
>>>
>>>     The reason it does not work with the library is that library
>>> objects are only included if they are referenced (to save executable
>>> size).
>>
>> That isn't true, the library is not passed to the linker as a library,
>> it's passed as an archive of object files.
>>
>> Forgive my ignorance of OPTLINK syntax, I'll make my point with linux
>> linker:
>>
>> dmd main.d mylib/libtest.a -> compile in all object files from libtest.a
>> dmd main.d -L-Lmylib -L-ltest -> only compile in parts of libtest.a that
>> are referenced
>>
> 	I just double checked and this is not true (at least with gnu ld
> v2.21.1, but AFAIR it never was true). Both forms only link in the
> parts of libtest.a that are referenced.

I could have sworn that passing an archive was like passing all the .o  
files.

>
>> In spite of all this, such inlining or optimizations are only made if
>> you use -O or -inline.  And I think just importing the module includes  
>> it.
>>
> 	Have you disassembled the object file to make sure? Have you tried
> using x (for example printing it) to see what happens?

I know inlining does not happen unless -inline is passed.  No need to  
check the output.

An easier check is to compile main.d without passing mylib/test.  If it  
doesn't need anything from the object file, it will link, right?

-Steve


More information about the Digitalmars-d mailing list