1. 程式人生 > 實用技巧 >uboot 新增 自定義命令

uboot 新增 自定義命令

--- title: uboot-uboot 新增 自定義命令 date: 2020-05-13 16:51:38 categories: tags: - uboot - cmd - config ---

章節描述:

定製化uboot 的時偶爾需要新增自定義命令,本問介紹如何新增命令。

步驟

新增命令檔案

在common目錄下,新建一個cmd_xx.c,需要新增的命令格式為:

int do_hello(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])

並在檔案中使用 U_BOOT_CMD 巨集進行有關說明 :

U_BOOT_CMD(name, maxargs, repeatable, command, "usage","help")

巨集引數有6個:

  • 第一個引數:新增的命令的名字
  • 第二個引數:新增的命令最多有幾個引數(注意,假如你設定的引數個數是3,而實際的引數個數是4,那麼執行命令會輸出幫助資訊的)
  • 第三個引數:是否重複(1重複,0不重複)(即按下Enter鍵的時候,自動執行上次的命令)
  • 第四個引數:執行函式,即運行了命令具體做啥會在這個函式中體現出來
  • 第五個引數:幫助資訊(short)
  • 第六個引數:幫助資訊(long)

最簡單的命令檔案的範例

#include <command.h>
#include <common.h>

int do_hello(cmd_tbl_t *cmdtp,int flag,int argc,char *argv)
{
    printf("my test \n");
    return 0;
}

U_BOOT_CMD(
hello,1,0,do_hello,"usage:test\n","help:test\n"
);

修改 Makefile

修改 common/Makefile 在Makfile中新增一行:

COBJS-y += cmd_xx.o 

附錄 : 巨集U_BOOT_CMD 的解析

#define U_BOOT_CMD(name,maxargs,rep,cmd,usage,help) \
  cmd_tbl_t   __u_boot_cmd_##name Struct_Section = {#name, maxargs, rep, cmd, usage, help}

我們分段來看:

命令所在的段:

#define Struct_Section __attribute__ ((unused,section (".u_boot_cmd")))

由定義可知該命令在連結的時候連結的地址或者說該命令存放的位置是u_boot_cmd section

巨集展開的結構體:

typedef struct cmd_tbl_s        cmd_tbl_t  struct cmd_tbl_s {
  char   *name;          /* Command Name    */
  int   maxargs;        /* maximum number of arguments  */
  int   repeatable;     /* autorepeat allowed?          */
                 /* Implementation function      */
  int   (*cmd)(struct cmd_tbl_s *, int, int, char *[]);
  char  *usage;         /* Usage message        (short) */
  char  *help
}