博客
关于我
C++如何在主函数(main)运行之前打印hello world
阅读量:525 次
发布时间:2019-03-08

本文共 1188 字,大约阅读时间需要 3 分钟。

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

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

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

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

方法一:

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

#include 
using namespace std;class app{ public: //构造函数 app() { cout<<"First"<

方法二:

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

#include 
using namespace std;int f(){ printf("before"); return 0;}int _ = f();int main(){ return 0;}

方法三:

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

#include
__attribute__((constructor)) void func(){ printf("hello world\n");}int main(){ printf("main\n"); //从运行结果来看,并没有执行main函数}

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

#include
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

你可能感兴趣的文章
MySQL - 解读MySQL事务与锁机制
查看>>
MTTR、MTBF、MTTF的大白话理解
查看>>
mt_rand
查看>>
mysql /*! 50100 ... */ 条件编译
查看>>
mudbox卸载/完美解决安装失败/如何彻底卸载清除干净mudbox各种残留注册表和文件的方法...
查看>>
mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>