c/c++:在main之前运行指定代码

File : before_main.cpp
Type : c/c++
Brief : 在main之前运行指定代码


#include <iostream>

// 全局变量赋值
int bm_func1()
{
    std::cout << "Before main: func1n";
    return 0;
}
int _bmf1 = bm_func1(); // 或者 static int _bmf1 = bm_func1();
int _bmf2 = []() //或者 static int _bmf2 = []()
{
    std::cout << "Before main: func2n";
    return 0;
}();

// gcc,clang 可用
void __attribute__((constructor)) bm_func3()
    //或者static void __attribute__((constructor)) bm_func3()
{
    std::cout << "Before main: func3n";
};

// 全局类的构造函数
class BmClass
{
public:
    BmClass()
    {
        std::cout << "Before main: classn";
    }
};
BmClass _bmc; // 或者 static BmClass _bmc;


int main()
{
    std::cout << "In main functionn";
    return 0;
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 [ [email protected] ]