I need additional initialization over existing in dynamic-linked application.
+1
A:
If you're writing a shared library that needs specific startup initialisation, you can use the GCC "constructor" extension:
void foo() __attribute__ ((constructor))
caf
2009-10-06 01:40:01
+2
A:
If you want to hook additional code before running main()
in an already-compiled program, you can use a combination of the constructor
attribute, and LD_PRELOAD
like so:
#include <stdio.h>
void __attribute__((constructor)) init() {
printf("Hello, world!\n");
}
Compile and run:
$ gcc -shared demo_print.c -o demo_print.so -fPIC
$ LD_PRELOAD=$PWD/demo_print.so true
Hello, world!
If you don't want to run normal main()
at all, just terminate (with exit()
etc) before main()
runs. Note that you won't be able to actually get the address of main()
to call manually - just return from your constructor to continue normal startup.
bdonlan
2009-10-06 01:53:35