4 ms·
If you think C code doesn't run before main() you're very naive. Just try this: #include <stdio.h> static volatile int* x; static int y = 42; void __attribut
by kllrnohj 9y ago
If you think C code doesn't run before main() you're very naive. Just try this:
#include <stdio.h>
static volatile int* x;
static int y = 42;
void __attribute__((constructor)) foo() {
printf("[foo] x = %p\n", x);
}
int main() {
x = &y;
printf("[main] x = %p\n", x);
return 0;
}
And before you complain about that being a compiler extension yes, it is, but it's also not rare, either, and you're probably using C libraries that do this.
- bb88 9y agoIt's a compiler "hack" for shared libraries, because there is no other way to run initialization for elf objects. [1] The C standard doesn't allow it. And gcc forces you to be explicit about it. [1]: https://www.geeksforgeeks.org/__attribute__constructor-__attribute__destructor-syntaxes-c/ https://www.geeksforgeeks.org/__attribute__constructor-__att...
- fnord123 9y ago>And before you complain about that being a compiler extension yes, it is, but it's also not rare, either, and you're probably using C libraries that do this. e.g. All Linux kernel modules use this for initialising static structs for interfacing with the kernel.