1利用C庫函數printf。
步驟:
1)首先需要包含頭文件stdio.h。
2)然后定義文件句柄。實際上就是一個int型變量封裝在結構體中。
struct__FILE{inthandle;};
3)定義FILE__stdout;FILE即為__FILE,通過stdio.h宏定義。
4)實現函數
intfputc(intch,FILE*f){chartempch=ch;sendchar(tempch);returnch;}
5)實現函數
intsendchar(intch){
if(ch=='n'){
while(!(console_tty_f->lsr&UART_LSR_THRE));
console_tty_f->dll_fifo=0x0d;
}
while(!(console_tty_f->lsr&UART_LSR_THRE));
return(console_tty_f->dll_fifo=ch);
}
由以上代碼可見,printf為阻塞函數,采用等待發(fā)完的辦法,可能影響其它進程。如果編寫非等待的打印函數,可以采用第二種方法。
2利用C庫函數vsprintf和變參函數。
步驟:
1)包含頭文件stdio.h和stdarg.h。
2)編寫變參數函數。
voidprint(constchar*lpszFormat,...){charszBuffer[PRINT_BUF]={0};
va_listargs;intret;va_start(args,lpszFormat);
ret=vsprintf(szBuffer,lpszFormat,args);
va_end(args);
uart[console_uart].put_2_ring(console_uart,szBuffer,ret);
}
由此可見,利用庫函數vsprintf格式化輸入字符串,然后在空閑時發(fā)送。
3自行完成參數提取,格式化。
步驟:
1)定義可變參數列表typedefchar*va_list;
2)定義地址對齊宏
#define_AUPBND(sizeof(int)-1)
#define_ADNBND(sizeof(int)-1)
#define_bnd(X,bnd)(((sizeof(X))+(bnd))&(~(bnd)))
3)定義可變長參數提取宏
#defineva_start(ap,A)(void)((ap)=(((char*)&(A))+(_bnd(A,_AUPBND))))
#defineva_arg(ap,T)(*(T*)(((ap)+=(_bnd(T,_AUPBND)))-(_bnd(T,_ADNBND)))
#defineva_end(ap)(void)0
4)編寫變參數函數。如方法2第2步。
5)實現vsprintf函數。實現源碼較多,如linux等。只是沒有對浮點的支持。