我正在阅读微软的CRT源代码,我可以想出下面的代码,其中函数__initstdio1将在main()例程之前执行。如何在VC中进入main()例程之前执行一些代码?
问题是,如何在VC(不是VC++代码)中输入main()例程之前执行一些代码?
#include <stdio.h>
#pragma section(".CRT$XIC",long,read)
int __cdecl __initstdio1(void);
#define _CRTALLOC(x) __declspec(allocate(x))
_CRTALLOC(".CRT$XIC") static pinit = __initstdio1;
int z = 1;
int __cdecl __initstdio1(void) {
z = 10;
return 0;
}
int main(void) {
printf("Some code before main!\n");
printf("z = %d\n", z);
printf("End!\n");
return 0;
}
输出将是:
Some code before main!
z = 10
End!
不过,我无法理解的代码。
我已经做了一些谷歌.CRT $ XIC,但没有找到运气。一些专家能解释一下上面的代码段对我来说,尤其是如下:
- 是什么线
_CRTALLOC(".CRT$XIC") static pinit = __initstdio1;
是什么意思?变量pinit的意义是什么? - 在编译期间,编译器(cl.exe时)抛出一个警告说,如下:
微软(R)32位C/C++优化编译器版15.00.30729.01为80x86的 版权(C)微软公司。版权所有。
stdmacro.c
stdmacro.c(9) : warning C4047: 'initializing' : 'int' differs in levels of indirection from 'int (__
cdecl *)(void)'
Microsoft (R) Incremental Linker Version 9.00.30729.01
Copyright (C) Microsoft Corporation. All rights reserved.
/out:stdmacro.exe
stdmacro.obj
需要做什么样的纠正措施才能删除警告消息?
在此先感谢。
补充:
我已经修改了代码,并作为PINIT给_PIFV类型。现在警告信息消失了。
新的代码如下:
#include <stdio.h>
#pragma section(".CRT$XIC1",long,read)
int __cdecl __initstdio1(void);
typedef int (__cdecl *_PIFV)(void);
#define _CRTALLOC(x) __declspec(allocate(x))
_CRTALLOC(".CRT$XIC1") static _PIFV pinit1 = __initstdio1;
int z = 1;
int __cdecl __initstdio1(void) {
z = 100;
return 0;
}
int main(void) {
printf("Some code before main!\n");
printf("z = %d\n", z);
printf("End!\n");
return 0;
}
这是一个好主意。 但是你的代码只能通过C++编译;不在C. – yinyueyouge 2009-04-08 08:02:03
问题标记为C++ – mouviciel 2009-04-08 08:16:19