gpt4 book ai didi

c - __attribute __((constructor))在VC中是否等效?

转载 作者:行者123 更新时间:2023-12-01 14:58:05 25 4
gpt4 key购买 nike

我想知道是否可以在VC中使用C构造函数,就像在GCC中使用它们一样。
使用__attribute__关键字的gcc方法非常简单,不幸的是VC似乎甚至都不知道该关键字,因为我不是Win32程序员,所以我想知道是否存在某种等效的关键字。
请注意-这是C程序,甚至不是C++或C#(因为用这些语言很容易做到)

最佳答案

下面的C代码演示了如何定义在main执行之前在程序/库加载时调用的void(void)函数。

对于MSVC,这会将指针指向用户初始化程序部分(.CRT $ XCU)中的函数,与编译器为构造函数调用静态C++对象所做的基本相同。对于GCC,使用构造函数属性。

    // 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;
}

关于c - __attribute __((constructor))在VC中是否等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60221352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com