我正在閱讀微軟的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