1

my c program calls:

hLibrary = dlopen("libPCBUSB.dylib", RTLD_LAZY);

and I seem to need this file in the directory when I run the executable after calling gcc main.c.

i.e. I run ./a.out and it all works as long as the dylib is in that directory.

In order to produce an executable with that dylib statically built in I've been trying all sorts of linking options but failing.

What is the correct way to compile my c program (in macOS Darwin not linux) to include this lib so the end user will not need it on their Mac?

pmdj
  • 22,018
  • 3
  • 52
  • 103
Andrew Arrow
  • 4,248
  • 9
  • 53
  • 80
  • Why do want to do a late binding by using `dlopen()` when *also* linking the lib to be bound late? If you link the lib you do not need late binding, as you could call the lib's function directly, as the lib is linked. – alk Jun 15 '19 at 09:56
  • sorry, very new to c, can you explain more? I would love to change this code anyway needed to make it so the final executable contains everything it needs. – Andrew Arrow Jun 15 '19 at 14:22

1 Answers1

3

Dynamic libraries (.dylib) can't be statically linked. If you have access to the source code for building the library, you can convert it to a static library and statically link against it in your app. If this is a 3rd-party binary-only library, you will need to ask the vendor for a static version of the library, and if that's not available, you will need to stick with linking it dynamically.

Note that dlopen() is not the only way to link against a dylib, you can also use -l, then you don't need to mess around with dlsym() etc. to get to the entry points. Either way requires shipping the library with your app of course.

pmdj
  • 22,018
  • 3
  • 52
  • 103
  • I don't think you can link statically on macOS - even with the source. I'm happy to be corrected, so if anyone knows different, kindly provide a link to something that shows how to do it and ping me. Thanks. – Mark Setchell Jun 16 '19 at 09:41
  • @MarkSetchell Of course you can. `.a` files exist on macOS (and indeed iOS, tvOS, etc.) like on many other UNIX-like systems. For example in Xcode, create a new project or target, select "Library", then in the "Type" drop-down, select "Static". – pmdj Jun 16 '19 at 10:19
  • Sorry, I meant with `gcc` as per OP's question. – Mark Setchell Jun 16 '19 at 10:22
  • @MarkSetchell I believe `gcc` doesn't include its own linker, you will need to use `ar` to create the `.a` file from object files (`.o`, created by whatever compiler you like) just like on GNU-based systems. – pmdj Jun 16 '19 at 11:02
  • so if I _have_ to include this file, could I literally encode the binary data of the file into a c int array and then use that binary data in the program vs. a separate file? – Andrew Arrow Jun 17 '19 at 02:09