How does libc provide functions with two names?

这一生的挚爱 提交于 2019-11-28 04:48:17

问题


Before the advent of direct binding (-B direct) libc provided many functions with two names. For example, getpwent() and _getpwent(). These two names referred to exactly the same function in libc.

How does libc make two function names point to the same implementation?

I think it should not be as easy as writing the same code twice though.


回答1:


It's done via weak aliases a "nonstandard" linker trick that's been around since early unices and that's supported by all unix compilers/linkers I know of. It's basically done as:

void __foo(void);
void foo(void) __attribute__((weak, alias("__foo")));

often with macros to abstract it a little bit. This makes it so the symbol foo will have the same address and type as the symbol __foo by default, but allows it to be overridden by a "strong" definition somewhere else.




回答2:


getpwent() implementation just calls _getpwent() simple as that. The reason this is done is to hide some functionality from function calls and to avoid something called namespace pollution. This way you can create a sort of abstraction that allows you to hide things from the user. Also leading underscore and double underscore are system reserved and are backups to make sure that you don't override something such as in macro definitions.



来源:https://stackoverflow.com/questions/6672607/how-does-libc-provide-functions-with-two-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!