What are static and dynamic binding in C (strictly C,not C++)?

被刻印的时光 ゝ 提交于 2021-02-18 03:38:10

问题


I had initial apprehensions about posting this question lest it be a duplicate.But even after googling with many keywords,I couldn't find any link on StackOverflow that explains static and dynamic binding for C.There are questions and answers for C++ though,but all involve classes and stuff that are clearly not for C.And the links outside StackExchange were quite dubious.

I need to know the rigorous definition and contrast between these two bindings,exclusively in the context of C.I would appreciate if you can take some time to answer it,or give me the links on StackOverflow for this lest I am mistaken and it has been answered in detail before.

I intend to have a clear idea about:

  1. Binding in C.
  2. Static vs dynamic binding in C.

Edit It would be immensely helpful if you could explain the difference with some simple code snippets.


回答1:


Formally, there are no such terms in "native" C.

Simplified explanation of the terms static binding ("early binding") and dynamic binding ("late binding"): they are most often used in object-orientated design, to determine whether the decision to call a particular inherited member function is done at compile time or in run time.

The meaning of a virtual function is that it's an inherited function which gets called instead of the equivalent function in the base class which was inherited. If the compiler can determine whether an object is of type "base class" or type "inherited class" at compile time, you get static binding, otherwise dynamic binding. So you would need some sort of runtime type information (RTTI).

In the above context, these terms only make sense if you are using object-oriented inheritance/polymorphism in your C program. C has no language support for such mechanisms. It is possible to implement them "manually" in C, but it is tedious and the code tends to be quite a mess. For those who insist, there is a book "Object oriented design in ANSI-C" which demonstrates how it can be done.

(Personally I would not recommend that book, nor to implement polymorphism in C. If you need those OOP feaures, just code in C++.)




回答2:


C is a statically compiled language, it doesn't really have "dynamic binding".

You can do it manually using API:s such as POSIX' dlopen(), but I would hesitate to call that "binding" although in a sense I guess it is.



来源:https://stackoverflow.com/questions/16420628/what-are-static-and-dynamic-binding-in-c-strictly-c-not-c

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