如何在 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\n",__func__);
    return;
}

void after(){
    printf("this is function %s\n",__func__);
    return;
}

int main(){
    printf("this is function %s\n",__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析构

猜你喜欢

转载自www.cnblogs.com/zpcoding/p/10805639.html