C++如何在主函数(main)运行之前打印hello world

主函数(main)运行之前打印hello world

主函数(main)运行之前打印hello world

主函数是永远是最先运行的函数,那么如果我们可不可以实现在主函数运行前在屏幕上打印一句话,比如“hello world”呢?

要想做到这点,首先明确一件事:对于在全局作用域中定义的对象,它们的构造函数是在文件中所有其他函数(包括主函数)开始执行前被调用的,对应的,析构函数是在终止main之后调用的。

方法一:

全局变量的构造函数,会在main之前执行。

#include <iostream>
using namespace std;

class app
{
public:
    //构造函数
    app()
    {
        cout<<"First"<<endl;
    }
};

app a;  // 申明一个全局变量

int main()
{
    cout<<"Second"<<endl;
    return 0;
}

方法二:

全局变量的赋值函数,会在main之前执行。(C中好像不允许通过函数给全局变量赋值)

#include <iostream>
using namespace std;

int f(){
    printf("before");
    return 0;
}

int _ = f();

int main(){
    return 0;
}

方法三:

如果是GNUC的编译器(gcc,clang),就在你要执行的方法前加上 attribute((constructor))

#include<stdio.h>

__attribute__((constructor)) void func()
{
    printf("hello world\n");
}

int main()
{
    printf("main\n"); //从运行结果来看,并没有执行main函数
}

同理,如果想要在main函数结束之后运行,可加上__sttribute__((destructor)).

#include<stdio.h>

void func()
{
    printf("hello world\n");
    //exit(0);
    return 0;
}

__attribute((constructor))void before()
{
    printf("before\n");
    func();
}


__attribute((destructor))void after()
{
    printf("after\n");

}

int main()
{
    printf("main\n"); //从运行结果来看,并没有执行main函数
}

参考

1、https://blog.csdn.net/weixin_43488167/article/details/90649159
2、https://www.cnblogs.com/lfri/p/12421251.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值