如何让一个函数在main函数之前调用

讨论

根据我们以往学习到的知识,c/c++程序的执行是main主函数开始执行的,
但是我们肯定也接触过全局对象变量,比如我们在main函数之外定义一个类的对象,然后在main函数内使用它,这是一个非常正常的操作。那么就以为着,在使用它的时候,我们已经调用了这个类的构造函数才能生成这个对象。这个构造函数的调用肯定在main函数开始执行之前就调用了!!!!
但是,这一切是编译器为我们做到的,那有没有一个方法能够让我们自己控制某一个函数让其执行在main函数之前呢,当然!!!
那就是

__attribute__((constructor))

这是一个gcc编译器特有的函数属性修饰符;它可以让函数在主函数之前就运行

#include <stdio.h>
#include <stdlib.h>

__attribute__((constructor)) static void load_file()
{
    printf("Constructor is called.\n");
}


int main()
{
    printf ("this is main function\n");
    return 0;
}

代码运行结果
在这里插入图片描述
同样的我们也可以使用

__attribute__((destructor))

来修饰函数,在主函数完成后执行该函数。

#include <stdio.h>
#include <stdlib.h>

__attribute__((constructor)) void load_file()
{
    printf("Constructor is called.\n");
}
__attribute__((destructor)) void unload_file()
{
    printf("destructor is called.\n");
}

int main()
{
    printf ("this is main function\n");
    return 0;
}

结果如下:
在这里插入图片描述
我最开始的是习惯用c++ 的cout<< 输出字符串但是下面这段代码出问题了!!!

#include <iostream>

 using namespace std;

 __attribute__((constructor))void  beforemain(void){
   cout<<"before main"<<endl;
   
}

__attribute__((destructor)) void aftermain(void){
    cout<<"after main"<<endl;
}
int main(){
    cout<<"before main"<<endl;
}

没有输出,很奇怪吧,思考思考!!!
我把beforemain()函数注释掉是能够正常输出的,而且使用printf()也能正常输出,这个时候,我的想法是,cout对象还没有初始化,所以使用cout会出问题。
标准流的自动初始化不会那么早发生。我们需要使用std::ios_base::Init强制它初始化。

#include <iostream>




void __attribute__((constructor)) myConstructor() {
    static std::ios_base::Init init;
    std::cout << "Hello from constructor function!" << std::endl;
}
    


void __attribute__((destructor)) aftermain()
{
    std::cout << "after main function" << std::endl;
}
 

int main(int argc,char** argv)
{
    std::cout << "in main function" << std::endl;
    return 0;
}

代码终于正常输出了!!!
在这里插入图片描述

[1]what does attribute(constructor)_ mean in c
[2]Why does this program fail to run properly, but it can output normally when I comment out the beforemain() function?

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值