Skip to content

Instantly share code, notes, and snippets.

@tenmyo
Last active December 21, 2016 07:18
Show Gist options
  • Save tenmyo/3b3e3acb56de3a868cbd45d56a66a643 to your computer and use it in GitHub Desktop.
Save tenmyo/3b3e3acb56de3a868cbd45d56a66a643 to your computer and use it in GitHub Desktop.
C言語でマルチプラットフォーム対応のコンストラクタ処理(MSVCでの__attribute__((constructor))相当など) ref: http://qiita.com/tenmyo/items/c3dd91af04d10d185a9a
// 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
static void finalize(void)
{
printf( "finalize\n");
}
INITIALIZER( initialize)
{
printf( "initialize\n");
atexit( 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