【发布时间】:2021-02-26 09:34:05
【问题描述】:
void someOtherFunction(void)
{
...
}
//Is it possible to call the #define like this, in the global scope? When does the execution come here?
SYSTEM_CONTROL_REGISTER_INIT_FUNCTION( credHandlerInit, LEVEL_APPLICATION, SYSTEM_CONTROL_ORDER_DONT_CARE );
void credHandlerInit(void)
{
portBASE_TYPE result;
result = xTaskCreate( credHandlerTask,
(portCHAR *) MBS_CFG_TASK_NAME_CRED_HANDLER,
MBS_CFG_TASK_STACK_CRED_HANDLER,
NULL,
MBS_CFG_TASK_PRIO_CRED_HANDLER,
&credHandlerTaskHandle );
}
在 .h 文件中定义了以下宏:
#define SYSTEM_CONTROL_REGISTER_INIT_FUNCTION( _initFunctionName, \
_initLevel, \
_initOrder ) \
\
void _initFunctionName( void ); \
\
SystemControlInitListRecord const systemControlInitRecord_ ## _initLevel ## _initOrder ## _ ## _initFunctionName \
__attribute__ ((section (".systemControlInitList"))) \
= { \
.name = #_initFunctionName, \
.syncedInitFunction = NULL, \
.unsyncedInitFunction = _initFunctionName, \
.level = _initLevel, \
.order = _initOrder, \
.initType = SYSTEM_CONTROL_RTOS_RUNNING \
}; \
\
void _initFunctionName( void )
我不明白的是这个函数是怎么调用的? 我在代码中没有看到对此函数的任何调用。 有人能解释一下这是如何工作的吗?
下面的代码是否有效,这样调用宏?
//main.c
#define SOMETHING(x) (someVariable = x)
static uint32_t someVariable;
SOMETHING(5);
int main(void)
{
printf("%d", someVariable); //should print 5 here then?
}
【问题讨论】:
-
对于下一个问题,提供一些minimal reproducible example 并给出编译命令。之前,请参考this C reference 网站。您可能还想阅读一些 C 标准,例如 n1570 或更好
-
带有宏的开源 C 代码示例包括 the Linux kernel 和 GNU emacs 和 Bismon 和 nwcc compiler。你可以下载他们的源代码并学习它以获得灵感
-
你也可以阅读Modern C这本书。它有专门介绍预处理器的章节(特别是第 16 节)
-
这很像一个关于如何不编写类似函数的宏的教程。由于类似函数的宏调用与宏使用的参数数量不匹配,因此代码也没有意义。这是真实代码的复制/粘贴吗?