Page 1 of 1

Linking to Static Libraries

Posted: Tue Oct 09, 2012 10:06 pm
by idle
When you try to link to a static library, you will often get a lot of undefined references

Methodology to resolve the problem

1) Add an Import to the library your linking to

Code: Select all

ImportC "libbar.a" : EndImport 
2) Add any Imports to know dependencies

Code: Select all

ImportC "libbar.a" : EndImport 
ImportC "-lstdc++" : EndImport   ;<------ 
3) Add Imports directly below the first import statement for a library that's reported an error eg undefined refference to foo ... first appears in libfoo

Code: Select all

ImportC "libbar.a" : EndImport 
ImportC "-libfoo" : EndImport   ; <------
ImportC "-lstdc++" : EndImport 

4) Add the functions to the library your linking to

Code: Select all

ImportC "libbar.a" : EndImport 
ImportC "-libfoo" : EndImport 
ImportC "-lstdc++" : EndImport  
ImportC "libbar.a"   ;<------ 
   foo()
   bar() 
EndImport 
Additionally some libraries may have multiple definitions and may still have unresolved symbols

Add these to the top

Code: Select all

ImportC "-Wl,--allow-multiple-definition" : EndImport   
ImportC "-Wl,--unresolved-symbols=ignore-in-object-files" : EndImport  ;use as a last resort  

ImportC "-libfoo" : EndImport 
ImportC "-lstdc++" : EndImport  
ImportC "libbar.a" 
   foo()
   bar() 
EndImport

Re: Linking to Static Libraries

Posted: Tue Oct 09, 2012 10:25 pm
by luis
Interesting, so are these linker flags ?
ImportC "-Wl,--allow-multiple-definition" : EndImport
ImportC "-Wl,--unresolved-symbols=ignore-in-object-files" : EndImport ;use as a last resort
Does this work under windows too ? The linker flag thing I mean.

Because this is definitely not documented, could be useful!

Thanks.

Re: Linking to Static Libraries

Posted: Tue Oct 09, 2012 10:43 pm
by idle
Yes they're linker flags, the -Wl option specifies to gcc to pass the flags to the a linker

I don't know if you can do something similar on windows to set additional flags for polink
I've never encountered a situation where I've had to try.

Re: Linking to Static Libraries

Posted: Tue Nov 19, 2013 4:10 pm
by auser
Those linker flags works fine even with shared libs and OpenLibrary() stuff. Seems even helpful if you have a lib in a non-standard-path:

Code: Select all

ImportC "-Wl,-rpath=/opt/lib" : EndImport
This just solved my issue with GnutTLS 3.2.6. While older versions placed at /opt/lib just worked without issue via OpenLibrary() the new version compiled with the same flags refused to work without this for unknown reason (I tried to avoid calling some "export LD_LIBRARY_PATH=/opt/lib" or adding a further path into "/etc/ld.so.conf")