-
-
Save ohio813/7fadd91195845ac6ae842734b0add8fe to your computer and use it in GitHub Desktop.
Run code before main()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#ifdef _MSC_VER | |
#ifdef __cplusplus | |
#define CONSTRUCTOR_FUNC(func) \ | |
struct func##_constructor { \ | |
func##_constructor() { func(); } \ | |
}; \ | |
static func##_constructor func##_instance; | |
#else | |
#pragma section(".CRT$XCU", read) | |
#define CONSTRUCTOR_FUNC(func) \ | |
__declspec(allocate(".CRT$XCU")) void (*p_init_func)() = func; | |
#endif | |
#else | |
#define CONSTRUCTOR_FUNC(func) \ | |
static void func() __attribute__((constructor)); | |
#define DESTRUCTOR_FUNC(func) \ | |
static void func() __attribute__((destructor)); | |
#endif | |
static void my_constructor(void) { | |
printf("Constructor called before main()\n"); | |
} | |
CONSTRUCTOR_FUNC(my_constructor); | |
int main() { | |
printf("Hello from main!\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment