博客
关于我
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 Error Handling in Stored Procedures---转载
查看>>
MVC 区域功能
查看>>
MySQL FEDERATED 提示
查看>>
mysql generic安装_MySQL 5.6 Generic Binary安装与配置_MySQL
查看>>
Mysql group by
查看>>
MySQL I 有福啦,窗口函数大大提高了取数的效率!
查看>>
mysql id自动增长 初始值 Mysql重置auto_increment初始值
查看>>
MySQL in 太多过慢的 3 种解决方案
查看>>
MySQL InnoDB 三大文件日志,看完秒懂
查看>>
Mysql InnoDB 数据更新导致锁表
查看>>
Mysql Innodb 锁机制
查看>>
MySQL InnoDB中意向锁的作用及原理探
查看>>
MySQL InnoDB事务隔离级别与锁机制深入解析
查看>>
Mysql InnoDB存储引擎 —— 数据页
查看>>
Mysql InnoDB存储引擎中的checkpoint技术
查看>>
Mysql InnoDB存储引擎中缓冲池Buffer Pool、Redo Log、Bin Log、Undo Log、Channge Buffer
查看>>
MySQL InnoDB引擎的锁机制详解
查看>>
Mysql INNODB引擎行锁的3种算法 Record Lock Next-Key Lock Grap Lock
查看>>
mysql InnoDB数据存储引擎 的B+树索引原理
查看>>
mysql innodb通过使用mvcc来实现可重复读
查看>>