Linking C libraries with DMD

W.J. via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jan 21 16:43:05 PST 2016


On Thursday, 21 January 2016 at 23:07:06 UTC, jmh530 wrote:
> On Thursday, 21 January 2016 at 22:54:26 UTC, Dibyendu Majumdar 
> wrote:
>> On Thursday, 21 January 2016 at 22:49:06 UTC, jmh530 wrote:
>>>
>>> I'm not trying to created a shared library in D. My goal is 
>>> to use a shared library from C in D. Right now, I'm working 
>>> with a simple test case to make sure I could understand it 
>>> before working with the actual shared library I want to use.
>>>
>>> I recall some discussion in LearningD (don't have it in front 
>>> of me now) that different types of shared libraries are 
>>> needed on 32bit vs. 64bit because there is a different 
>>> linker. This is what I did to created the shared library:
>>>
>>> gcc -Wall -fPIC -c <file>.c -I.
>>> gcc -shared -o <libfile>.dll <file>.o -I.
>>> implib <libfile>.lib <libfile>.dll
>>
>> Okay then you don't need the /IMPLIB option. But you do need 
>> to specify the library via -L as I mentioned before.
>>
>> i.e. use:
>>
>> dmd -m64 -L/LIBPATH:<path to lib> -L<library name> prog.d
>>
>> Where <library name> is yourlib.lib and this is present along 
>> with the DLL in the path you gave.
>>
>> Plus your prog.d needs to have appropriate code. Example:
>>
>> module app;
>>
>> extern (C) void testing();
>>
>> void main()
>> {
>> 	testing();
>> }
>>
>> Here testing() is provided in the DLL.
>
> I ran
>
> dmd -m64 <file>.d -L/LIBPATH:<path to lib> -L<library name>
>
> and got
>
> <library name> : fatal error LNK1136: invalid or corrupt file
> --- errorlevel 1136
>
> At least that's progress.

The linker will most certainly get confused by  this "-L<library 
name>" - as it will take it for an object file. The difference is 
that a library is a collection of object files.

The GNU linker ld, for instance, uses the -l<libname> switch for 
adding libraries to link against and -L<path> to add a search 
path to look for the libraries passed in with -l<libname>.

If you leave it to the compiler to invoke the linker you need to 
remember the -L compiler switch is passing what follows to the 
linker (minus the -L compiler switch).
I.e. -L-LC:\lib\path will be passed on as "-LC:\lib\path", 
-L-lsomelib => "-lsomelib", etc.

You won't find help about linker options on any compiler manual. 
You have to refer to your linker manual.

Also make sure to adhere to naming conventions. It could very 
well be your linker quits with an error message if you pass it 
-lsomelib for a file somelib.lib when it expects to find the file 
libsomelib.lib instead.

> LNK1136 is for a corrupt or abnormally small file. I did notice 
> that the original dll was 82kb and the lib file was 2kb.

The lib for a 'DLL' is small because it just tells the linker 
where to find the code in the 'DLL' - the actual code is in the 
'DLL'.

Hope the helps


More information about the Digitalmars-d-learn mailing list