c - VC中进入main()例程前如何执行一些代码?

标签 c msvcrt crt

我正在阅读 Microsoft 的 CRT 源代码,我可以得出以下代码,其中函数 __initstdio1 将在 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 上做了一些谷歌搜索,但没有找到任何运气。有专家能给我解释一下上面的代码段吗,尤其是下面的:

  1. 这行 _CRTALLOC(".CRT$XIC") static pinit = __initstdio1; 是什么意思?变量pinit有什么意义?
  2. 在编译过程中,编译器 (cl.exe) 会发出如下警告:

Microsoft (R) 32 位 C/C++ 优化编译器版本 15.00.30729.01 for 80x86 版权所有 (C) Microsoft Corporation。保留所有权利。

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

最佳答案

一个简单的方法来做到这一点。

#include <iostream>

int before_main()
{
    std::cout << "before main" << std::endl;
    return 0;
}

static int n = before_main();

void main(int argc, char* argv[])
{
    std::cout << "in main" << std::endl;
}

关于c - VC中进入main()例程前如何执行一些代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/728939/

相关文章:

c - C 问题中的字符串操作

c - 初学者需要简单解释评估顺序和优先级/关联性之间的区别

c++ - 如何控制 Microsoft C 运行时库使用的 CPU 指令?

c++ - _CrtSetBreakAlloc 使用内存内容而不是分配号

c++ - 如何防止 CRT 错误 C++ 导致进程崩溃

c - 通过我的 C 程序打开 GnuPlot

c - 合并十六进制值中的位

winapi - 为什么_get_heap_handle 等于GetProcessHeap?

msvcrt - Windows 下的 MSVCRT 是否像 *nix 下的 glibc (libc)?

c++ - 这个 "CRT not initialized"错误是怎么回事?