看开源的代码中发现了一些静态函数声明后有如下内容:
__attribute__ ((constructor))
这是gcc的扩展属性,文档中说明如下:
The constructor attribute causes the function to be called automatically before execution enters main (). Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.
You may provide an optional integer priority to control the order in which constructor and destructor functions are run. A constructor with a smaller priority number runs before a constructor with a larger priority number; the opposite relationship holds for destructors. So, if you have a constructor that allocates a resource and a destructor that deallocates the same resource, both functions typically have the same priority. The priorities for constructor and destructor functions are the same as those specified for namespace-scope C++ objects (see C++ Attributes).
These attributes are not currently implemented for Objective-C.
简单的说,这两个属性定义的函数,分别在main函数前和main函数后(或exit后)执行。
示例程序:
执行结果:
$ ./test
508, start:
3904, end: in child 1
432, end: in child 2
508, end: in father