9

Can a static libary *.a in Linux be dynamically loaded at runtime?
I've read here that

...both static and shared libraries can be used as dynamically loaded libraries.

How to dynamically load static library?

3 Answers 3

12

A static library is more or less just a collection of object files. If you want to use a static library in a program, you have to link the executable with it. The executable will then contain the static library (or the parts that you used).

If you want to load a static library at runtime using dlopen, you will have to first create a dynamic library libfoo.so containing it.

Sign up to request clarification or add additional context in comments.

2 Comments

That workaround implies that I would have to create a shared library from a static library if I want to dynamically load it. This means that loading a static library dynamically is not possible and that only shared libraries can be used for dynamical loading? If so, than the quote I've stated from the source is not correct.
The quoted text is incorrect, or I am misinterpreting what they mean.
3

Opening a .a file using dlopen does not work (tested on Ubuntu 10.04). With the following example program:

#include <dlfcn.h>
#include <stdio.h>

int main()
{
  void *lib_handle = dlopen("/usr/lib/libz.a",RTLD_LAZY);
  printf("dlopen error=%s\n",dlerror());

  printf("lib_handle=%p\n",lib_handle);
}

I get:

dlopen error=/usr/lib/libz.a: invalid ELF header
lib_handle=(nil)

while when using /usr/lib/libz.so instead, I get:

dlopen error=(null)
lib_handle=0x19d6030

so the same code works for a shared object.

Comments

2

A .a is an archive containing one or more .o elf objects. Readelf and objdump won't parse them. You must use ar to xtract the .o files from the archive. It is important to realize that if you are willing to spend the time writing and debugging a variant of load_elf() that can wrap one or more static libraries in a HAL you can load them dynamically and provide clients with a way to introspect their call entry points. This is nonstandard, and I can already feel the literati twitching like The Walking Jed. However, the ELF contains enough information to drop a library into a runtime environment and give properly coded client functions a way to discover the interface to the functions provided, and call them. This isn't rocket science. It is simply tedious. An important concept here is that a developer who provides the .a archive and a include suite with the idea that they are restricting your use of the libraries, is just being annoying. It is not a serious impediment to using the library, or discovering how it does it's job.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.