C语言宏定义中的 ##

阅读: 评论:0

C语言宏定义中的 ##

C语言宏定义中的 ##

参考自keil的RTX源码:

/// Thread Definition structure contains startup information of a thread.
typedef struct os_thread_def  {os_pthread               pthread;    ///< start address of thread functionosPriority             tpriority;    ///< initial thread priorityuint32_t               instances;    ///< maximum number of instances of that thread functionuint32_t               stacksize;    ///< stack size requirements in bytes; 0 is default stack size
} osThreadDef_t;  // 定义结构体类型// 宏定义
#define osThreadDef(name, priority, instances, stacksz)  
const osThreadDef_t os_thread_def_##name = 
{ (name), (priority), (instances), (stacksz)  }osThreadDef(AppSysRunThread,osPriorityNormal,1,0);
// 定义一个结构体变量,同时进行初始化//宏定义osThreadDef展开的结果如下:
const osThreadDef_t os_thread_def_AppSysRunThread = 
{(AppSysRunThread), (osPriorityNormal), (1), (0)};//即:
const osThreadDef_t os_thread_def_AppSysRunThread = 
{ (AppSysRunThread), (osPriorityNormal), (1), (0),   
};

##”被称为连接符(concatenator),用来将两个Token连接为一个Token。注意这里连接的对象是Token就行,而不一定 是宏的变量。“##”前后可以有空格。

// 宏定义
#define A1(name, type)  type name_##type##_type 
#define A2(name, type)  type name##_##type##_type// 宏定义展开
A1(a1, int);  
// 等价于:
int name_int_type;A2(a2, int);  
// 等价于:
int a2_int_type;

需要注意的是凡宏定义里有用’#‘或’##'的地方宏参数是不会再展开的。

#define A   (2) 
define CONS(a,b)  int(a##e##b) printf("%sn", CONS(A, A));    // 这一行被展开为: 
printf("%sn", int(AeA)); // A都不会再被展开

参考来源:.html
参考来源:

自己想当然的尝试:

#include<stdio.h>
#include<string.h>#define TRANS(x) #x/*# ## 只能用在宏定义中*/unsigned char str[]=
{"hello" " "TRANS(world)  // 不能将 TRANS(world) 改为 #world   没有这样的用法"n"
};int main(void)
{printf("%s", str);printf("%ldn", sizeof(str));return 0;
}/*
运行结果如下:ubuntu@ubuntu:~$ ./a.out 
hello world
13
ubuntu@ubuntu:~$数组中的元素分别是:
'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' 'd' 'n' ''
*/

在上述的例子中,需要注意的一点是 hello 后面便没有""

本文发布于:2024-01-31 06:16:53,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170665302226136.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:定义   语言
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23