如何讓一段程序在main函數之前執行


方法一:

全局變量的構造函數,會在main之前執行。

#include <iostream>
using namespace std;

class app
{
public:
    //構造函數
    app()
    {
        cout<<"First"<<endl;
    }
};

app a;  // 申明一個全局變量

int main()
{
    cout<<"Second"<<endl;
    return 0;
}

方法二:

全局變量的賦值函數,會在main之前執行。(C中好像不允許通過函數給全局變量賦值)

#include <iostream>
using namespace std;

int f(){
    printf("before");
    return 0;
}

int _ = f();

int main(){
    return 0;
}

方法三:

如果是GNUC的編譯器(gcc,clang),就在你要執行的方法前加上 __attribute__((constructor))

#include<stdio.h>

__attribute__((constructor)) void func()
{
    printf("hello world\n");
}

int main()
{
    printf("main\n"); //從運行結果來看,並沒有執行main函數
}

同理,如果想要在main函數結束之后運行,可加上__sttribute__((destructor)).

#include<stdio.h>

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. CSDN_darmao-不執行main函數可以執行一段程序嗎?

2. CSDN_xuhongtao123459-如何讓一段程序在main函數之前執行

3. 知乎-C/C++中如何在main()函數之前執行一條語句?


免責聲明!

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



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