一、簡介
GNU 的 gperf 工具是一種 “完美的” 散列函數,可以為用戶提供的一組特定字符串生成散列表、散列函數和查找函數的 C/C++ 代碼。通過本文學習如何使用 gperf 實現 C/C++ 代碼中高效的命令行處理。
二、安裝
源碼下載
http://www.gnu.org/software/gperf/ https://savannah.gnu.org/projects/gperf
用戶手冊
http://www.gnu.org/software/gperf/manual/gperf.html http://www.cnblogs.com/napoleon_liu/archive/2010/12/27/1918057.html
三、實例
參考
http://blog.chinaunix.net/uid-9950859-id-98839.html http://www.ibm.com/developerworks/cn/linux/l-gperf.html
示例1:參數解析
首先,編寫.gperf 文件,此處以example1.gperf為例,內容如下
%{
/* C code that goes verbatim in output */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
%}
struct tl{ const char* name ; const char s2;};
%%
"--name",'n'
"--love",'l'
%%
int main(int argc,char **argv)
{
const struct tl * str2;
int i;
char *test;
for(i=1; i<argc; i++)
{
if((str2 = in_word_set(argv[i],strlen(argv[i]))) != 0)
{
switch (str2->s2)
{
case 'n':
test=argv[i+1];
printf("My name is %s.\n",test);
i++;
break;
case 'l':
printf("successed !\n");
break;
}
}
}
return 0;
}
然後,執行如下指令,將.gperf 文件轉換為.c文件
gperf -t -L C example1.gperf > example1.c
編譯
gcc -g -o example1 example1.c
運行