您的位置:首页 > 编程语言 > C语言/C++

在C++工程中main函数之前跑代码的廉价方法

2015-11-10 00:17 357 查看
// test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
#include <crtdbg.h>

/// 在C++工程中main函数之前跑代码的廉价方法
/// 利用全局变量可以赋可变初值的事实
/// mainCRTStartup() => _cinit() => 全局变量(静态, 普通)赋初值

extern "C" int foo(void);
extern "C" int foo1(void);

/// 执行顺序和全局变量声明顺序相同
/// 先执行foo1, 再执行foo();
static int gs_iTest = foo1();
int g_iTest = foo();

int main(int argc, char* argv[])
{
    printf("&main = %p\n", &main);
    getchar();
	return 0;
}

extern "C" int foo(void)
{
    /// 执行不带CRT函数的代码
    MessageBox(NULL, "foo before main", "test", MB_OK);
    return 0;
}

extern "C" int foo1(void)
{
    /// 执行不带CRT函数的代码
    MessageBox(NULL, "foo1 before main", "test", MB_OK);
    return 0;
}


效果





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: