Barry Wark
Barry Wark

Reputation: 107754

Force static linking of library linked to Xcode target?

My Xcode target links against hdf5 library (using the Link Binary with Libraries build phase). libhdf5 is installed using MacPorts, thus /opt/local/lib contains both the dynamic (.dylib) and static (.a) versions of the library.

The text output from the build shows that there is, as expected, a -lhdf5 in the linking step of the build. gcc seems to take the dynamic linked library over the static, however. Is there any way to force gcc (via a compiler switch or via Xcode) to statically link with libhdf5.a?

The only solution I've found is to copy libhdf5.a to the project (or other) directory and link against that copy, thus avoiding having dynamic and static versions in the same location.

Upvotes: 13

Views: 15034

Answers (5)

user500515
user500515

Reputation: 171

Had this exact same problem and despite this being an old post, I thought I'd share what I had to do to make this work.

Usually you do just provide the switch '-static' to the linker however, with Xcode this causes all libs including the crt to be linked statically. I got the error:

can't locate file for: -lcrt0.o

When I tried above.

What worked for me was to replace:

-lmylib

With:

/path/to/libmylib.a

Note that the -l is dropped.

Upvotes: 17

zwlxt
zwlxt

Reputation: 351

Under XCode 11.3.1, targeting MacOS

Tried to add absolute lib path to Other linker flags. But that doesn't work. So I copied required *.a files (ln -s may also work) to project dir and it worked like a charm.

Upvotes: 0

user272735
user272735

Reputation: 10648

My case with Xcode 4.5:

When I drag and drop a static C library (a 3rd party library compiled with GNU Autotools) to project's frameworks (Project Navigator > Frameworks) the linker seems to thinks that's a dynamic library and adds -L -l flags:

-L/path/to/libfoodir -lfoo

The linking fails because there is no /path/to/libfoodir/libfoo.dylib. The linker command can be seen from:

Log Navigator > select a Build log > select a Link line and expand it

The linking succeeds when I add a full path (/path/to/libfoodir/libfoo.a) to the linker settings:

Targets > Build Settings (all) > Other linker flags

Upvotes: 3

yungchin
yungchin

Reputation: 1599

In reaction to your comment on Eduard Wirch' answer: you can also control static linking for this one library only, if you replace -lhdf5 by -l/full/path/to/libhdf5.a

Upvotes: 8

Eduard Wirch
Eduard Wirch

Reputation: 9922

Use the "-static" switch for linking: GCC link options

Upvotes: 2

Related Questions