宏定义__FILE__,__LINE__,__VA_ARGS__等介绍与应用

ANSIC标准定义中常见的预定义宏

__LINE__:在源代码中插入当前源代码行号;

__FILE__:在源代码中插入当前源代码路径及文件名;

__DATE__:在源代码中插入当前编译日期;

__TIME__:在源代码中插入当前编译时间(编译时间,而非运行时的时间);

__STDC__:当要求程序严格遵循ANSIC标准时,该标识符赋值为1;

__cplusplus:当编写C++程序时该标识符被定义;

__VA_ARGS__:可变参数宏,用__VA_ARGS__代表用(…)表示的形参。

预定义宏应用举例

预定义宏常用域打印调试信息,如下例中,以gd32f30x环境为例,打印出程序运行中的提示或问题:

#include "gd32f30x.h"
#include <stdio.h>
#include "gd32f307c_eval.h"
#include "stdarg.h"

void uart_configuration(void);
int fputc(int ch, FILE *f);

#define ERROR_PRINT(PFORMAT,...)  error_print(__FILE__, __func__, __LINE__, PFORMAT, __VA_ARGS__)

void error_print(const char *file, const char *func, int line, const char *format,...)
{
    va_list vaargs;
    va_start(vaargs,format);
    printf("error occured in file:%s ,in function:%s ,on line: %d. ",file,func,line);
    vprintf(format,vaargs);
    return;
}

void uart_configuration(void)
{
    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_USART0);
    
    gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);
    gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_10);
    
    usart_deinit(USART0);
    usart_baudrate_set(USART0, 115200U);
    usart_receive_config(USART0, USART_RECEIVE_ENABLE);
    usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);
    usart_enable(USART0);
    
    ERROR_PRINT("%s","error:RCU_GPIOB not enable");
}

int main(void)
{
    uart_configuration(); 
    
    while(1) {}
}

/* retarget the C library printf function to the USART */
int fputc(int ch, FILE *f)
{
    usart_data_transmit(USART0, (uint8_t)ch);
    while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));
    return ch;
}

程序输出结果:

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值