opc0de
opc0de

Reputation: 11768

Function which gets executed on library load

I am pretty new in developing Shared Libraries for the Linux platform.

Is there a function that I can define inside the .SO that will be called upon the load of the library by dlopen() ?

Upvotes: 1

Views: 1499

Answers (3)

beyrem
beyrem

Reputation: 436

from man page: The obsolete symbols _init() and _fini() The linker recognizes special symbols _init and _fini. If a dynamic library exports a routine named _init(), then that code is executed after the loading, before dlopen() returns. If the dynamic library exports a routine named _fini(), then that routine is called just before the library is unloaded. In case you need to avoid linking against the system startup files, this can be done by using the gcc(1) -nostartfiles command-line option.

   Using these routines, or the gcc -nostartfiles or -nostdlib options,
   is not recommended.  Their use may result in undesired behavior,
   since the constructor/destructor routines will not be executed
   (unless special measures are taken).

   **Instead, libraries should export routines using the
   __attribute__((constructor)) and __attribute__((destructor)) function
   attributes.  See the gcc info pages for information on these.
   Constructor routines are executed before dlopen() returns, and
   destructor routines are executed before dlclose() returns.**

Upvotes: 1

user529758
user529758

Reputation:

If you are using GCC or a compatible compiler, you can declare a function with __attribute__((constructor)) and it will be called upon load. Something like

__attribute__((constructor))
void init()
{
    puts("Hello dynamic linkage world!");
}

Upvotes: 4

John Zwinck
John Zwinck

Reputation: 249542

No, there is no standard "entry point" in a shared object defined by the system. A given application that uses dlopen() is likely to define a standard symbol name to be used as the entry point for modules loaded this way. The host application would then use dlsym() to look up that symbol by name in order to invoke it.

But most applications do not use dlopen directly at all--and you haven't explained why you think you should.

Upvotes: 2

Related Questions