讨论
根据我们以往学习到的知识,c/c++程序的执行是main主函数开始执行的,
但是我们肯定也接触过全局对象变量,比如我们在main函数之外定义一个类的对象,然后在main函数内使用它,这是一个非常正常的操作。那么就以为着,在使用它的时候,我们已经调用了这个类的构造函数才能生成这个对象。这个构造函数的调用肯定在main函数开始执行之前就调用了!!!!
但是,这一切是编译器为我们做到的,那有没有一个方法能够让我们自己控制某一个函数让其执行在main函数之前呢,当然!!!
那就是
__attribute__((constructor))
这是一个gcc编译器特有的函数属性修饰符;它可以让函数在主函数之前就运行
#include <stdio.h>
#include <stdlib.h>
__attribute__((constructor)) static void load_file()
{
printf("Constructor is called.\n");
}
int main()
{
printf ("this is main function\n");
return 0;
}
代码运行结果
同样的我们也可以使用
__attribute__((destructor))
来修饰函数,在主函数完成后执行该函数。
#include <stdio.h>
#include <stdlib.h>
__attribute__((constructor)) void load_file()
{
printf("Constructor is called.\n");
}
__attribute__((destructor)) void unload_file()
{
printf("destructor is called.\n");
}
int main()
{
printf ("this is main function\n");
return 0;
}
结果如下:
我最开始的是习惯用c++ 的cout<< 输出字符串但是下面这段代码出问题了!!!
#include <iostream>
using namespace std;
__attribute__((constructor))void beforemain(void){
cout<<"before main"<<endl;
}
__attribute__((destructor)) void aftermain(void){
cout<<"after main"<<endl;
}
int main(){
cout<<"before main"<<endl;
}
没有输出,很奇怪吧,思考思考!!!
我把beforemain()函数注释掉是能够正常输出的,而且使用printf()也能正常输出,这个时候,我的想法是,cout对象还没有初始化,所以使用cout会出问题。
标准流的自动初始化不会那么早发生。我们需要使用std::ios_base::Init强制它初始化。
#include <iostream>
void __attribute__((constructor)) myConstructor() {
static std::ios_base::Init init;
std::cout << "Hello from constructor function!" << std::endl;
}
void __attribute__((destructor)) aftermain()
{
std::cout << "after main function" << std::endl;
}
int main(int argc,char** argv)
{
std::cout << "in main function" << std::endl;
return 0;
}
代码终于正常输出了!!!
[1]what does attribute(constructor)_ mean in c
[2]Why does this program fail to run properly, but it can output normally when I comment out the beforemain() function?