You may have noticed that the descriptions of ccall() and cwrap() specified that both are used to call a compiled C function. The omission of C++ was intentional because an additional step is needed to call functions from a C++ file. C++ supports function overloading, which means that you can use the same function name multiple times, but pass different arguments to each one to get a different result. Here's an example of some code that uses function overloading:
int addNumbers(int num1, int num2) {
return num1 + num2;
}
int addNumbers(int num1, int num2, int num3) {
return num1 + num2 + num3;
}
int addNumbers(int num1, int num2, int num3, int num4) {
return num1 + num2 + num3 + num4;
}
// The function will return a value based on how many
// arguments you pass it:
int getSumOfTwoNumbers = addNumbers(1, 2);
// returns 3
int getSumOfThreeNumbers = addNumbers(1, 2, 3);
// returns 6
int getSumOfFourNumbers = addNumbers(1, 2, 3, 4);
// returns 10
The compiler needs to differentiate between these functions. If it used the name addNumbers and you tried calling the function in one place with two arguments and another with three, it would fail. To call the function by name in your compiled Wasm, you need to wrap the function in an extern block. One implication of wrapping the function is that you would have to explicitly define functions for each condition. The following code snippet demonstrates how to implement the previous functions without name mangling:
extern "C" {
int addTwoNumbers(int num1, int num2) {
return num1 + num2;
}
int addThreeNumbers(int num1, int num2, int num3) {
return num1 + num2 + num3;
}
int addFourNumbers(int num1, int num2, int num3, int num4) {
return num1 + num2 + num3 + num4;
}
}