An answer to this question brought __attribute__((constructor))
to my attention, however, for reasons I don't fully understand, I observed a SIGSEGV
when using that if the void function used std::cout
(printf
did not cause the SIGSEGV
).
I posted a version of this question earlier (but stupidly deleted it). An answerer at that time pointed me to this excellent article which discusses the situation and solution:
http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html
Excerpt of the solution (modified slightly to pass compilation) is here:
#include <cstdio>
#include <cstdlib>
void preinit(int argc, char * * argv, char * * envp) {
printf("%s\n", __FUNCTION__);
}
void init(int argc, char * * argv, char * * envp) {
printf("%s\n", __FUNCTION__);
}
void fini() {
printf("%s\n", __FUNCTION__);
}
__attribute__((section(".init_array"))) typeof (init) * __init = init;
__attribute__((section(".preinit_array"))) typeof (preinit) * __preinit = preinit;
__attribute__((section(".fini_array"))) typeof (fini) * __fini = fini;
void __attribute__((constructor)) constructor() {
printf("%s\n", __FUNCTION__);
}
void __attribute__((destructor)) destructor() {
printf("%s\n", __FUNCTION__);
}
void my_atexit() {
printf("%s\n", __FUNCTION__);
}
void my_atexit2() {
printf("%s\n", __FUNCTION__);
}
int main() {
atexit(my_atexit);
atexit(my_atexit2);
}
(Apologies to the original answerer that I deleted my original post and can't give due credit.)