Avoid linking in unused symbols when linking against static libs
Asked Answered
S

1

3

I'm using the apple gcc to compile a dylib that I'm going to redistribute. For various reasons I'm using some libraries, let's say libz to keep it simple.

Since this library is not typically found on a Mac system I wish to static link in used symbols into the dylib by passing the path to the .a-file to simplify deployment.

Now, the linker links in all symbols from the lib into the resulting dylib although I only reference a subset. On linux I've never encountered this problem, the linker happily discards all unreferenced symbols and creates a very slim executable, so it should be possible. The dylib file I have now is ~10 times larger than it should.

I've tried fiddle around with the -dead_code linker flag, but to no avail. Perhaps I just don't understand it?

Does anyone know the solution to this?

Subway answered 8/4, 2011 at 7:25 Comment(0)
M
5

Try -Wl,--gc-sections.

As regards -dead_strip (what you probably meant by -dead_code):

Before turning on the -dead_strip option your project will first have to be "ported" to work with dead code stripping. This will include changing from -gused (the default for -g) to -gfull and re-compiling all of the objects files being linked into your program with the new compiler from the Mac OS X June 2004 release. Also if your building an executable that loads plugins, which uses symbols from the executable, you will have to make sure the symbols the plugins use are not stripped (by using attribute((used)) or the -exported_symbols_list option). If you are using an export list and building a shared library, or an executable that will be used with ld(1)'s -bundle_loader flag, you need to include the symbols for exception frame information in the export list for your exported C++ symbols. These symbols end with .eh and can be seen with the nm(1) tool.

and:

To enable dead-code stripping from the command line, pass the -dead_strip option to ld. You should also pass the -gfull option to GCC to generate a complete set of debugging symbols for your code. The linker uses this extra debugging information to dead strip the executable.

Hope this helps.

All content in this answer was located within the first few Google search results for "apple ld static link unused symbols". :)

Montanez answered 8/4, 2011 at 9:6 Comment(1)
thanks for googleing this up. Compiling on mac yeilds "Mach-O" objects as opposed to ELF which I beleive are used with the --gc-sections switch. I tried the -gfull switch together with the -dead_strip but to no avail.Subway

© 2022 - 2024 — McMap. All rights reserved.