Skip to content

Instantly share code, notes, and snippets.

@rdnvndr
Forked from tenmyo/initializer.c
Last active November 29, 2023 14:17
Show Gist options
  • Save rdnvndr/e726c0b45faec1aa240fe88b89437358 to your computer and use it in GitHub Desktop.
Save rdnvndr/e726c0b45faec1aa240fe88b89437358 to your computer and use it in GitHub Desktop.
Initializer/finalizer sample for MSVC and GCC/Clang.
// c - __attribute__((constructor)) equivalent in VC? - Stack Overflow
// http://stackoverflow.com/questions/1113409/attribute-constructor-equivalent-in-vc/2390626#2390626
// Rev.5
// Initializer/finalizer sample for MSVC and GCC/Clang.
// 2010-2016 Joe Lowe. Released into the public domain.
#include <stdio.h>
#include <stdlib.h>
#ifdef __cplusplus
#define INITIALIZER(f) \
static void f(void); \
struct f##_t_ { f##_t_(void) { f(); } }; static f##_t_ f##_; \
static void f(void)
#elif defined(_MSC_VER)
#pragma section(".CRT$XCU",read)
#define INITIALIZER2_(f,p) \
static void f(void); \
__declspec(allocate(".CRT$XCU")) void (*f##_)(void) = f; \
__pragma(comment(linker,"/include:" p #f "_")) \
static void f(void)
#ifdef _WIN64
#define INITIALIZER(f) INITIALIZER2_(f,"")
#else
#define INITIALIZER(f) INITIALIZER2_(f,"_")
#endif
#else
#define INITIALIZER(f) \
static void f(void) __attribute__((constructor)); \
static void f(void)
#endif
#define INIT_LIBRARY(init, fin) \
INITIALIZER(initialize1) \
{ \
init(); \
atexit(fin); \
}
static void finalize()
{
printf( "finalize\n");
}
static void initialize()
{
printf( "initialize\n");
}
INIT_LIBRARY(initialize, finalize)
int main( int argc, char** argv)
{
printf( "main\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment