overexchange
overexchange

Reputation: 1

Linking shared library to executable

libourown.so provides function f definition

After execution of gcc command,

gcc a.o libourown.so.1 -o app

1)

Does libourown.so get linked to app at runtime , when f is called in app? or Does libourown.so gets linked to app at build time?

2)

Does libc.so get linked at runtime to app, after printf is called in app ? or Does libc.so gets linked to app at build time?

Upvotes: 4

Views: 15585

Answers (4)

Anjaneyulu
Anjaneyulu

Reputation: 434

To answer your "Does libourown.so get linked to app at runtime , when f is called in app? or Does libourown.so gets linked to app at build time?"

Dynamic libraries are linked as soon as they are brought into ram. The same answer valid for both of your questions. This type of linking done is known as load time linking.

Another method of doing it is to use the concept of run time linking. Using functions like dlopen(), dlsym()

Upvotes: 1

Dmitry Grigoryev
Dmitry Grigoryev

Reputation: 3203

It's impossible to statically link to a .so file: this file is missing information which is necessary for the linker to work. If you need to statically link to libourown.so, you have two options:

  • generate the static version of the library, libourown.a, and link against that

  • use a tool like statifier to embed libourown.so in your executable.

Libc is linked to executables dynamically by default. You can link to it statically using -static option. It should be noted that statically linking to libc will do more harm than good, because other libraries your executable is using are likely to be linked agains libc dynamically, and linking to the same library twice leads to a disaster.

Upvotes: 1

P.P
P.P

Reputation: 121427

The answer is same to both of your questions. The shared libraries are not built into your executable (that's one of the main reasons why they came into existence in the first place!). When you run your app, the drynamic linker/loader ld.so loads the necessary libraries.

You can see the shared libraries needed by your application by running:

$ ldd ./app

on the command line.

You may find this very useful to understand shared libraries on Linux: how to write shared libraries

Upvotes: 2

Delights
Delights

Reputation: 449

The whole point of a shared object is that it won't be linked statically to your executable, but rather sit in the memory and serve those who need it.

Look at this thread: how can I link a shared object in C?

Upvotes: 0

Related Questions