c - 如何定义具有多个名称的函数

标签 c gcc alias

我想用多个名称声明以下函数:

static __inline__ int square(int i) {
  return i * i;
}

它只需要与 GCC 4.x 一起工作(对于一些有用的 x 值)

我试过 __asm__,但它只适用于非静态函数,所以这行不通:

static __inline__ int square2(int i) __asm__("square");

我试过 alias,但它阻止了对 square2 的调用被内联,但我想内联 squaresquare2,等价地。

static __inline__ int square2(int i) __attribute__((alias("square2")));

我已经尝试了一个宏,但这阻止了我在其他不相关的函数中使用名为 squaresquare2 的独立局部变量。所以我不能接受这个:

#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/

相关文章:

c - 如何将字符映射到另一种类型的指针?

C编程: How to make program end when user inputs a newline

c++ - 为什么我不能运行目标文件?

c++ - GCC如何优化这个 `switch`

mysql - 如何对连接表执行查询?

C 用 exec() 和 fork() 对字符串数组进行排序;

c++ - -fshort-wchar 和 std::wstring - 段错误

git - 定义具有相同名称的 git 别名以 stash 原始命令

mysql - MySQL 中的 "Not unique table/alias"

c - 链表,分配字符数组 [C]