Interview Preparation topic: Name Mangling
You might have seen some code covered with extern "C" keyword in your c++ code.
Let’s discuss why we need this keyword in c++.
As we all know c++ allows function overloading, a code can have multiple functions with similar names but with different implementations.
Consider the following code snippet(main.cpp)
As you can see we have two methods with same name 'addition'. But two functions have different arguments.
At the time of compile, compiler uses 'name mangling' to distinguish between this two.
If we see the object file generated by the compiler. We can see that compiler has added some prefix as well as postfix to the name of the method. (Not going in to detail).
But in that process, it has changed the name of interruputHandler function as well.
Interrupt handlers are registered in the startup code with predefined names, for example ‘UART0_IRQHandler’ is registered for UART0 interrupt.
At run time system, cannot get the predefined handler name (because of name mangling) and it will report an error.
To remove this error, we need to surround the handler code with extern “C”. This will inform compiler and this function will not get name mangled.
Now interruptHandler function is not name mangled.