I write code in C99 and compile via GCC. I would like to use function overloading for stylistic reasons (otherwise I would have to do name mangling by myself).
I have read Is there a reason that C99 doesn't support function overloading? however, I still wonder whether it can be enabled in GCC.
Can you help me at this point?
No, there is no function overloading in C99, not even in silly GCC extensions. C11 adds _Generic
, but even then you still have to mangle names yourself.
void foo_int(int x);
void foo_double(double x);
#define foo(arg) _Generic((arg), int: foo_int, double: foo_double)(arg)
Whether that's better or worse, well. It's C.
In C macros may partially replace function overloading of other languages. As Cat Plus Plus indicates in her answer C11 has the additional construct _Generic
to program type generic macros.
With C99 you already have possibilities to program macros that are in some sense type generic. P99 has facilities that ease the use of that, e.g to call such a macro with a different number of parameters. To distinguish which function to call according to a specific parameter A
you could then use something like (sizeof(A) == sizeof(float) ? sqrtf(A) : sqrt(A))
.
Gcc has extensions that allow to program such things even more comfortably, namely block expressions with ({ any code here })
and typeof
to declare auxiliary variables of the same type as a macro parameter.
LLVM Clang3.3 has introduced function overloading. In fact, function overloading might not so easy as you expect. It involves such problems as function-call convention and ABI(Application Binary Interface). When you mix your C code with assembly language, those problems may occur.
When you work with assembly procedures, the names of the exported procedures should not be overloaded.
In LLVM Clang, you can do this with attribute (overloadable):
static void __attribute__((overloadable)) MyFunc(float x)
{
puts("This is a float function");
}
static int __attribute__((overloadable)) MyFunc(int x)
{
puts("This is an integer function");
return x;
}