Created
December 21, 2016 06:11
-
-
Save tenmyo/dde01e838cdaf14c8353fbad03ab9bc8 to your computer and use it in GitHub Desktop.
Initializer/finalizer sample for MSVC and GCC/Clang.
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
// 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 | |
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