Zusammenfassung der Überprüfung und Verwendung von __attribute__ ((Konstruktor))
Beachten Sie, dass es aufgrund der Erweiterung von GCC nicht überall funktioniert.
main.c
#include <stdio.h>
__attribute__((constructor))
static void constructor() {
puts("constructor");
}
__attribute__((destructor))
static void destructor() {
puts("destructor");
}
int main(int argc, char const* argv[])
{
puts("call main");
return 0;
}
Ergebnisse erstellen und ausführen
$ gcc main.c && ./a.out
constructor
call main
destructor
main.c
#include <stdio.h>
int main(int argc, char const* argv[])
{
puts("call main");
return 0;
}
sharedlib.c
#include <stdio.h>
__attribute__((constructor))
static void constructor() {
puts("constructor");
}
__attribute__((destructor))
static void destructor() {
puts("destructor");
}
Ergebnisse erstellen und ausführen
$ gcc -shared -fPIC sharedlib.c -o libconstructor.so
$ gcc main.c -L . -lconstructor
$ LD_LIBRARY_PATH=. ./a.out
constructor
call main
destructor
Mit LD_PRELOAD können Sie später jedem Programm eine Verarbeitung hinzufügen.
main.c
#include <stdio.h>
int main(int argc, char const* argv[])
{
puts("call main");
return 0;
}
preload.c
#include <stdio.h>
__attribute__((constructor))
static void constructor() {
puts("constructor");
}
__attribute__((destructor))
static void destructor() {
puts("destructor");
}
Ergebnisse erstellen und ausführen
$ gcc main.c && ./a.out
call main
$ gcc -shared -fPIC preload.c -o preload.so
$ LD_PRELOAD=./preload.so ./a.out
constructor
call main
destructor
__attribute__ ((Konstruktor))
gibtEs funktioniert gut, auch wenn es mehrere attribute ((Konstruktor)) gibt. (Die Ausführungsreihenfolge ist jedoch unbekannt, und es scheint besser, eine Verarbeitung zu vermeiden, die von der Ausführungsreihenfolge abhängt.)
main.c
#include <stdio.h>
__attribute__((constructor))
static void constructor1() {
puts("constructor1");
}
__attribute__((destructor))
static void destructor1() {
puts("destructor1");
}
int main(int argc, char const* argv[])
{
puts("call main");
return 0;
}
preload.c
#include <stdio.h>
__attribute__((constructor))
static void constructor2() {
puts("constructor2");
}
__attribute__((destructor))
static void destructor2() {
puts("destructor2");
}
Ergebnisse erstellen und ausführen
$ gcc main.c && ./a.out
constructor1
call main
destructor1
$ gcc -shared -fPIC preload.c -o preload.so
$ LD_PRELOAD=./preload.so ./a.out
constructor2
constructor1
call main
destructor1
destructor2
Rufen Sie eine Funktion vor dem main () -bk-Blog auf c++ - How exactly does attribute((constructor)) work? - Stack Overflow Versuchen Sie, das __attribute __ ((Konstruktor)) von GCC: Book of Days zu verwenden gcc - C++ static initialization vs attribute((constructor)) - Stack Overflow