Linux内核关键字讲解

嵌入式技术

1332人已加入

描述

gcc attribute 关键字用来给 函数、变量、数据类型设置属性

属性

C语言代码里看到__attribute__这个东西,它就是表示要描述属性了。gcc的通用属性可以参考Common-Function-Attributes。

alias

alias格式

alias ("target")

alias属性可以给target符号起一个别名,两个名字用起来效果一样。

1、attribute alias变量格式

extern 类型 新变量名字 __attribute__((alias("旧变量名字")));

2、attribute alias函数格式

extern 类型 新函数名字(参数) __attribute__((alias("旧函数名字")));

备注:新的函数别名需要和旧函数类型相同,即函数返回值和参数要相同;alias后函数名称只写函数名字即可,无需携带括号和参数。

代码演示

  • 代码中有一个void __printPath(const char *path)函数的完整定义,main函数对其进行了调用,传值为命令行传入的文件路径/home/TEST/BAR/tmp。
  • printPath是一个新名字,它和__printPath是等价的,即它是__printPath的别名。注意因为__printPath带参数,所以printPath必须带参数,且类型需和__printPath一致。
  • Debug是一个新名字,它和__myfunc是等价的,即它是__myfunc的别名。
  • date是一个变量别名,与__date等价。 注意这里只能给全局变量起别名
#include < stdio.h >
#include < stdlib.h >

/* __attribute__((alias()))为函数和变量起别名 */
/* printPath(const char* path)为__printPath(const char* path)的别名 */
extern void printPath(const char* path) __attribute__((alias("__printPath")));
/* Debug()为__myfunc()函数的别名 */
extern void Debug() __attribute__((alias("__myfunc")));

/* date变量为__date变量的别名 */
extern char* date  __attribute__((alias("__date")));

/* 定义全局变量__date */
char* __date="2023-01-18";

void __printPath(const char *path)
{
    printf("The %s file in the %s folder.\\n", __FILE__, path);
}

void __myfunc()
{
    printf("You are calling the function %s in %s file.\\n",__FUNCTION__, __FILE__);
}

void printDate()
{
    fprintf(stdout,"Today is:%s\\n", date);
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        printf("Please input the correct parameter, it need a parameter with the file path!\\n");
        exit(-1);
    }

    printf("=========================================================\\n");
    printPath(argv[1]);
    Debug();
    printDate();
    printf("=========================================================\\n");
    return 0;
}

编译程序,执行结果如下:

[root@localhost tmp]# gcc -o alias alias.c
[root@localhost tmp]# ./alias /home/TEST/BAR/tmp
=========================================================
The alias.c file in the /home/TEST/BAR/tmp folder.
You are calling the function __myfunc in alias.c file.
Today is:2023-01-18
=========================================================

注意 :如果别名目标(target)与别名不在同一个翻译单元中定义,则是一个错误。在没有属性的情况下,GCC假定带有外部链接的不同声明表示不同的对象。在没有声明别名属性的翻译单元中,使用别名和别名目标来访问同一个对象是没有定义的。此属性需要汇编程序和对象文件支持,并且可能不适用于所有目标。

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分