0%

__attribute__((alias))函数属性

说明

官方文档说明如下:

This function attribute enables you to specify multiple aliases for a function.

Aliases must be defined in the same translation unit as the original function.

此函数属性使您可以为函数指定多个别名。

别名必须在与原始函数相同的翻译单元中定义。

1
2
3
4
5
6
7
8
9
10
11
12
static struct config __internal_config;		///< 全局静态内部配置

struct config *libmp_get_multipath_config(void)
{
if (!__internal_config.hwtable)
/* not initialized */
return NULL;
return &__internal_config;
}

struct config *get_multipath_config(void)
__attribute__((alias("libmp_get_multipath_config")));

示例

在输出对象文件中,编译器将别名调用替换为对原始函数名称的调用,并在原始名称旁边发出别名。 例如:

1
2
3
4
5
6
7
static int oldname(int x, int y) {
return x + y;
}
static int newname(int x, int y) __attribute__((alias("oldname")));
int caller(int x, int y) {
return oldname(x,y) + newname(x,y);
}

该代码编译为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
AREA ||.text||, CODE, READONLY, ALIGN=2
newname ; Alternate entry point
oldname PROC
MOV r2,r0
ADD r0,r2,r1
BX lr
ENDP
caller PROC
PUSH {r4,r5,lr}
MOV r3,r0
MOV r4,r1
MOV r1,r4
MOV r0,r3
BL oldname
MOV r5,r0
MOV r1,r4
MOV r0,r3
BL oldname
ADD r0,r0,r5
POP {r4,r5,pc}
ENDP

如果原始函数定义为 static 但别名定义为 extern,则编译器将原始函数更改为外部函数。

  • 该函数属性是ARM编译器支持的GNU编译器扩展。

  • 变量名称也可以使用相应的变量属性来命名。__attribute__((alias))

语法

1
return-type newname([argument-list]) __attribute__((alias("oldname")));
  • oldname 需要设置别名的函数名称。
  • newname 是别名函数的新名称。

例子

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
void foo(void)
{
printf("%s\n", __FUNCTION__);
}
void bar(void) __attribute__((alias("foo")));
void gazonk(void)
{
bar(); // calls foo
}

reference

[1]https://developer.arm.com/documentation/dui0472/k/Compiler-specific-Features/--attribute----alias---function-attribute

小主,路过打个赏再走呗~