问题描述
嘿,
我在想,如果有可能使用C语言构造在VC只是因为它有可能在GCC使用它们。
gcc的方法是相当直接使用的属性关键字,遗憾的是VC似乎并不知道这个关键字,因为我不是一个Win32程序员,我不知道是否有一些这样的事情相当于关键字。
只是要注意的 - 这是一个C程序,而不是C ++或C#甚至,(因为它是个很容易做,在这些语言)
Hey,I was wondering if it's possible to use C constructors in VC just as it is possible to use them in GCC.The gcc way is quite straight using the attribute keyword, unfortunately VC doesn't seem to even know this keyword, as I'm not a Win32 programmer I wonder if there's some sort of equivalent keyword for such things.Just to note - this is a C program, not a C++ or C# even, (as 'twas quite easy to do that in those languages)
任何人都得到了线索?
Anyone got a clue ?
先谢谢了。
推荐答案
C以下code演示了如何定义一个void(无效)函数在程序/库加载时被调用,主要执行之前。
Below C code demonstrates how to define a void(void) function to be called at program/library load time, before main executes.
有关MSVC,这个地方一个函数指针在用户初始化部分(.CRT $ XCU),基本上是编译器的构造同样的事情要求静态C ++对象。对于GCC,使用一个构造属性。
For MSVC, this places a pointer to the function in the user initializer section (.CRT$XCU), basically the same thing the compiler does for the constructor calls for static C++ objects. For GCC, uses a constructor attribute.
// 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;
}
这篇关于__attribute __((构造函数)),相当于在VC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!