如何在 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析構

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM