zoukankan      html  css  js  c++  java
  • 如何在 main() 执行之前先运行其它函数

    摘要:我们知道 C++ 的全局对象的构造函数会在 main 函数之前先运行,其实在 c 语言里面很早就有啦,在 gcc 中可以使用 __attribute__ 关键字指定如下(在编译器编译的时候就绝决定了)

    在 C 语言中 用 __attribute__ 关键字

    #include <stdio.h>
    
    void before() __attribute__((constructor));
    void after() __attribute__((destructor));
    
    void before() {
        printf("this is function %s
    ",__func__);
        return;
    }
    
    void after(){
        printf("this is function %s
    ",__func__);
        return;
    }
    
    int main(){
        printf("this is function %s
    ",__func__);
        return 0;
    }
    
    // 输出结果
    // this is function before
    // this is function main
    // this is function after

    在 C++ 中用全局对象构造函数

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class A {
    public:
        A(string s) {
            str.assign(s);
            cout << str << ":A构造" <<endl;
        }
        ~A(){
            cout << str << ":A析构" <<endl;
        }
    private:
        string str;
    };
    
    A test1("Global"); // 全局对象的构造
    
    int main() {
        A test2("main");  // 局部对象的构造
        return 0;
    }
    
    // 输出结果
    // Global:A构造
    // main:A构造
    // main:A析构
    // Global:A析构
    所有博文均为原著,如若转载,请注明出处!
  • 相关阅读:
    quick-cocos2dx 3.5集成protobuf
    lua和luajit在cocos2dx mac模拟器的简单测试
    cocos2dx-lua手游客户端框架设计
    cocos2dx动画技术选型
    lua中的面向对象
    html 学习
    OC 与js 互相调用
    Carthage的安装和使用
    Bomb后端云使用
    FMDB简单使用
  • 原文地址:https://www.cnblogs.com/zpcoding/p/10805639.html
Copyright © 2011-2022 走看看