博客
关于我
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-触发器及创建触发器失败原因
查看>>
MySQL-连接
查看>>
mysql-递归查询(二)
查看>>
MySQL5.1安装
查看>>
mysql5.5和5.6版本间的坑
查看>>
mysql5.5最简安装教程
查看>>
mysql5.6 TIME,DATETIME,TIMESTAMP
查看>>
mysql5.6.21重置数据库的root密码
查看>>
Mysql5.6主从复制-基于binlog
查看>>
MySQL5.6忘记root密码(win平台)
查看>>
MySQL5.6的Linux安装shell脚本之二进制安装(一)
查看>>
MySQL5.6的zip包安装教程
查看>>
mysql5.7 for windows_MySQL 5.7 for Windows 解压缩版配置安装
查看>>
Webpack 基本环境搭建
查看>>
mysql5.7 安装版 表不能输入汉字解决方案
查看>>
MySQL5.7.18主从复制搭建(一主一从)
查看>>
MySQL5.7.19-win64安装启动
查看>>
mysql5.7.19安装图解_mysql5.7.19 winx64解压缩版安装配置教程
查看>>
MySQL5.7.37windows解压版的安装使用
查看>>