我想用多个名称声明以下函数:
static __inline__ int square(int i) {
return i * i;
}
它只需要与 GCC 4.x 一起工作(对于一些有用的 x 值)
我试过 __asm__
,但它只适用于非静态函数,所以这行不通:
static __inline__ int square2(int i) __asm__("square");
我试过 alias
,但它阻止了对 square2
的调用被内联,但我想内联 square
和 square2
,等价地。
static __inline__ int square2(int i) __attribute__((alias("square2")));
我已经尝试了一个宏,但这阻止了我在其他不相关的函数中使用名为 square
和 square2
的独立局部变量。所以我不能接受这个:
#define square2 square
我知道写另一个调用,但我不喜欢它,因为它是优化器的另一个间接,并且它可能会在某些复杂的情况下阻止内联:
static __inline__ int square2(int i) { return square(i); }
还有其他解决方案吗?
最佳答案
我猜您的“真实”代码具有比单个语句更复杂的功能?否则显而易见的选择是用第二个名字重复定义。
当然你可以把它变成一个宏:
#define SQUARE_BODY(a) return (a) * (a);
static inline square(int x)
{
SQUARE_BODY(x);
}
static inline square2(int x)
{
SQUARE_BODY(x);
}
当然,您可以将更多的函数定义折叠到宏中,但我认为仅将其作为主体部分会使代码的其余部分更加清晰。
关于c - 如何定义具有多个名称的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26451875/