开发者

How do I get the GCC __attribute__ ((constructor)) to work under OSX?

extern void MyInitFunc(void)开发者_Go百科 __attribute__ ((constructor));
extern void MyTermFunc(void) __attribute__ ((destructor));

void MyInitFunc(void)
{
  printf("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n");
}

void MyTermFunc(void)
{
}

I put this in a .c file which is present in the main application (not a library or framework). It doesn't get called as per the GCC docs. Am I missing something important? This is on XCode 3.2 on Snow Leopard.


This might explain some of the strange bugs being reported on Snow Leopard, but only if this construct worked in earlier releases.

You are correct that MyInitFunc should have been called purely as a result of being linked in with the program, even if the program is plain C89, even if the rest of it is some other language entirely.

The problem is that the C startup code on your system is not looking at the .ctors section and the .dtors section for addresses of constructors and destructors. I'm not sure if this is true of all platforms, but normally this is __do_global_ctors, a part of libgcc.

It's a platform bug, or, your gcc was built wrong, or, Apple has simply decided to do things differently and gcc doesn't support the platform properly.

You might try cc -v ... and check that collect2 is being called instead of ld directly.


(a) Your code works for me compiling and running on SnowLeopard in Xcode 3.2.

(b) I'm not sure when stdout is guaranteed to have been set up. You're running code before main. Why not update a global variable here, then print it out in main to see if your code ran.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜