1.C语言程序必须从main函数开始吗?
这是在面试中被问到的一个问题,回答了是。这问题第一感觉答案就是否定的,一时也没想出来理由只能回答了是。当时太紧张了,其实回想一下汇编语言就该想到程序的入口地址是可以指定的,c语言编译器默认以main作为入口地址。
网上查阅后,发现了 __attribute__ 这个关键字,它可以设置函数属性,变量属性,类型属性。
参考:http://www.cnblogs.com/Anker/p/3462363.html
看下面的例子:
// gcc 编译器
#include<stdio.h>
__attribute__((constructor)) void before_main()
{
printf("%s\n",__FUNCTION__);
}
__attribute__((destructor)) void after_main()
{
printf("%s\n",__FUNCTION__);
}
int main()
{
printf("%s\n",__FUNCTION__);
return 0;
}
可以看到上面的程序并不是从main函数开始执行的。constructor 设置在main前面执行,destructor 设置在main之后执行。
2.main函数执行完后还执行其他语句吗?
有时候需要有一种与程序退出方式无关的方法来进行程序退出时的必要处理,方法就是用atexit()函数来注册程序正常终止时要被调用的函数,atexit()函数的参数是一个函数指针,函数指针指向一个没有参数也没有返回值的函数,它的原型是
int atexit(void (*)(void));
具体实现可以参考一下代码:
#include <stdlib.h>
#include <stdio.h>
void fn1(void);
void fn2(void);
int main(void)
{
atexit(fn1);
atexit(fn2);
printf("main exit ...\n");
return 0;
}
void fn1()
{
printf("calling fn1()...\n");
}
void fn2()
{
printf("calling fn2()...\n");
}
程序运行结果:
3 main 函数执行前还会执行什么代码
首先进行全局对象的构造,然后进入main函数
#include <iostream>
using namespace std;
class Test
{
public :
Test()
{
cout<<"construct of the Test"<<endl;
}
};
Test a;
int main()
{
cout<<"main start"<<endl;
Test b;
return 0;
}
运行结果如图: