How portable is weak linking? #pragma weak my_symbol

寵の児 提交于 2019-12-08 01:41:06

问题


How portable is weak linking?

#pragma weak my_symbol

I see that question: how-to-make-weak-linking-work-with-gcc discusses how to get it working. But is there a good way to do this such that gcc is not required?

What is the difference between weak linking and guarding the declartion with an #ifdef?

#ifndef my_weak_fn
    void my_weak_fn(){/* Do nothing */ return;}
#endif

回答1:


#pragma is, by definition, not portable.

And weak linking is done at link time (surprisingly enough). It allows a function (or any symbol, really) with the same signature to override another. That means a strong one will be chosen in preference to the weak one but, if there's no strong one, the weak one will be used.

Include guards are done by the compiler, not the linker, and they do not allow the fallback to a weak one if the strong one's not there. You can simulate the same behavior if you control the source for both functions (by ifdef-ing for one, ifndef-ing for the other) but that's not always the case and this is more choosing between two strong functions.

Weak linking allows you to do things like drop in your own malloc()/free() for debugging purposes while still linking with the library that provides them.



来源:https://stackoverflow.com/questions/1410811/how-portable-is-weak-linking-pragma-weak-my-symbol

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