简体   繁体   English

GCC:允许在C99中重载功能

[英]GCC: Allow overloaded functions in C99

I write code in C99 and compile via GCC. 我在C99中编写代码并通过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? 我读过有没有理由说C99不支持函数重载? however, I still wonder whether it can be enabled in GCC. 但是,我仍然想知道它是否可以在GCC中启用。

Can you help me at this point? 你能帮助我吗?

No, there is no function overloading in C99, not even in silly GCC extensions. 不,C99中没有函数重载,即使在愚蠢的GCC扩展中也没有。 C11 adds _Generic , but even then you still have to mangle names yourself. C11添加了_Generic ,但即便如此,你仍然需要自己修改名称。

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. 这是C.

In C macros may partially replace function overloading of other languages. 在C宏中,可能会部分替换其他语言的函数重载。 As Cat Plus Plus indicates in her answer C11 has the additional construct _Generic to program type generic macros. 正如Cat Plus Plus在她的回答中指出的那样,C11具有额外的构造_Generic来编程类型通用宏。

With C99 you already have possibilities to program macros that are in some sense type generic. 使用C99,您已经可以编写某种意义上通用的宏。 P99 has facilities that ease the use of that, eg to call such a macro with a different number of parameters. P99具有易于使用它的功能,例如,使用不同数量的参数调用这样的宏。 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)) . 要根据特定参数A来区分调用哪个函数,您可以使用类似(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. Gcc具有允许更加舒适地编程这些事物的扩展,即使用({ any code here })typeof块表达式来声明与宏参数相同类型的辅助变量。

LLVM Clang3.3 has introduced function overloading. LLVM Clang3.3引入了函数重载。 In fact, function overloading might not so easy as you expect. 事实上,函数重载可能并不像你期望的那么容易。 It involves such problems as function-call convention and ABI(Application Binary Interface). 它涉及诸如函数调用约定和ABI(应用程序二进制接口)之类的问题。 When you mix your C code with assembly language, those problems may occur. 当您将C代码与汇编语言混合使用时,可能会出现这些问题。 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): 在LLVM Clang中,您可以使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM