Skip to content

Instantly share code, notes, and snippets.

@ohio813
Forked from whokilleddb/main.cc
Created August 3, 2025 22:00
Show Gist options
  • Save ohio813/7fadd91195845ac6ae842734b0add8fe to your computer and use it in GitHub Desktop.
Save ohio813/7fadd91195845ac6ae842734b0add8fe to your computer and use it in GitHub Desktop.
Run code before main()
#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