13

Do shared libraries (.so) files need to present (or specified) at link time?

I've read here (Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?) that .so files must be present at compile time, but in my experience this is not true?

Doesn't shared libraries just get linked at runtime using dlopen and dlsym, so that the library may not be present on the system, when the application is linked?

Community
  • 1
  • 1
Shuzheng
  • 11,288
  • 20
  • 88
  • 186
  • Just search this site for questions with "undefined reference", you'll see that there are cases when it is necessary. I'd argue the majority, manual `dlopen` is rather specialized use. – Mat Feb 03 '17 at 06:13
  • 1
    When is it necessary and when is it not? – Shuzheng Feb 03 '17 at 06:15
  • 1
    Try compiling a piece of code that calls `dlopen`, without the `-ldl` link flag. It is necessary "almost always" for normal use of shared libraries. – Mat Feb 03 '17 at 06:19
  • compile-time: no; link-time: yes; run-time:yes. On some platforms (AIX for example), you can use _import-files_ when linking instead of the shared libraries. – Lorinczy Zsigmond Feb 03 '17 at 10:19

2 Answers2

7

Most shared libraries need to be present both at build time and at run time. Notice that shared libraries are not DLLs (which is a Windows thing).

I assume you code for Linux. Details are different on other OSes (and they matter).

For example, if you are compiling a Qt application, you need the Qt shared libraries (such as /usr/lib/x86_64-linux-gnu/libQt5Gui.so and many others) both when building your application and when running it. Read about the dynamic linker ld-linux.so(8) & about ELF.

But you are asking about dynamic loading (using dlopen(3) with dlsym(3) ...) of plugins. Then read Levine's Linkers & Loaders, Program Library HowTo, C++ dlopen mini HowTo, and Drepper's How To Write Shared Libraries

See also this answer.

Some libraries and frameworks try to abstract the loading of plugins in an OS-neutral manner. Read e.g. about Qt plugins support, or about POCO shared libraries (poorly named, it is about plugins).

Andrew Moylan
  • 2,893
  • 18
  • 20
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • So, can a shared library always be used for dynamic loading? Is the reason why the .so file must be specified at link time that the program explicitly refers to functions in calls, and not indirectly using dlopen()? – Shuzheng Feb 03 '17 at 06:40
  • 1
    You need to read all the references I have given to you (and you'll need more than a week to read all of that). Details are operating system specific. – Basile Starynkevitch Feb 03 '17 at 06:42
  • Thank you, I will! – Shuzheng Feb 03 '17 at 07:20
-1

You can have it both way, it all works.

While with library present at compile time,instead of get library by dlopen/LoadLibrary explictly, you can use all the functions directly

hyphen
  • 369
  • 3
  • 4