In the book Thinking in C++, it mentioned about type-safe linkage, but not very clear.Can someone explain it in detail? Thanks in advance.
Typesafe linkage enforces the right number and type of parameters are passed at link time.
For example, in C, you can define a library function as taking an int, but through a series of mishaps, you can pass it a string.
C++ avoids this kind of error by making function prototypes mandatory and my using name mangling to enforce typesafe linking.Source
Lets see by one example
//:Def.cpp
void f(int) {}
//Use.cpp
// Function misdeclaration
void f(char);
int main() {
f(1); // Causes a linker error
}
function is actually f(int)
, the compiler doesn’t know this because it was told through an explicit declaration – that the function is f(char).compilation will be successful. In C, the linker would also be successful, but not in C++.
A very detailed explanation is also given here http://www.hpc.unimelb.edu.au/nec/g1af05e/chap9.html
Type-safe linkage enforces that one has to provide the correct number and types of arguments at link-time. As a counter-example consider C, where you can define a function which takes an double
but you accidentally pass a complex
. In C++ this cannot happen due to type-safe linkage. As reference, have a look at Type-Safe Linkage for C++
Edit wrapup: C++ uses name mangling. This also enables overloading of functions, where the function signature must be unique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With