ANSIC标准定义中常见的预定义宏
LINE:在源代码中插入当前源代码行号;
FILE:在源代码中插入当前源代码路径及文件名;
DATE:在源代码中插入当前编译日期;
TIME:在源代码中插入当前编译时间(编译时间,而非运行时的时间);
STDC:当要求程序严格遵循ANSIC标准时,该标识符赋值为1;
__cplusplus:当编写C++程序时该标识符被定义;
VA_ARGS:可变参数宏,用__VA_ARGS__代表用(...)表示的形参。
预定义宏应用举例
预定义宏常用域打印调试信息,如下例中,以gd32f30x环境为例,打印出程序运行中的提示或问题:
cpp
#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;
}
程序输出结果: