Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the so called "type-safe linkage" in C++?

Tags:

c++

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.

like image 262
EXLsunshine Avatar asked Sep 05 '25 16:09

EXLsunshine


2 Answers

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

like image 131
Ankur Avatar answered Sep 07 '25 17:09

Ankur


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.

like image 37
Sebastian Dressler Avatar answered Sep 07 '25 17:09

Sebastian Dressler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!