比較適用於大量參數的數組,下標獲取值(提升代碼效率)
兩個頭文件:
List.h :
//List.h "aaa", "bbb", "ccc",
List2.h
//List2.h aaa, bbb, ccc,
初始化enum:
#ifndef TTT_H_ #define TTT_H_ enum { #include "List2.h" NR_OF_OBJECT_COMMANDS }; #endif /* TTT_H_ */
main.c:
#include <stdio.h> #include "ttt.h" char *objectMnemonic[] = { #include "List.h" }; int main() { printf("aaa = %d\n",aaa); // 枚舉 printf("NR_OF_OBJECT_COMMANDS = %d\n",NR_OF_OBJECT_COMMANDS); // 枚舉 printf("objectMnemonic = %s\n",objectMnemonic[1]); // 字符串數組下標 獲取 字符串
printf("objectMnemonic = %s\n",objectMnemonic[aaa]); // 下標是枚舉,獲取對應字符串,這才是核心
// 還可以應用到多個字符串和對應的值(類似c++的map),比如obj[one] = 1;(這個數組可以手動初始化)
return 0; }
gcc 版本 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)
Console:
aaa = 0
NR_OF_OBJECT_COMMANDS = 3
objectMnemonic = bbb
objectMnemonic = aaa
疑問1:我把List.h 重命名為List.c 頭文件也包含改為List.c
不知道為什么報錯:
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"List.d" -MT"List.d" -o "List.o" "../List.c"
../List.c:2:1: error: expected identifier or ‘(’ before string constant
"aaa",
^
make: *** [List.o] Error 1
疑問2: List2.h 改為 List2.c 也會報錯,不知道為什么。
如下:
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"List2.d" -MT"List2.d" -o "List2.o" "../List2.c"
../List2.c:2:1: warning: data definition has no type or storage class [enabled by default]
aaa,
^
../List2.c:2:1: warning: type defaults to ‘int’ in declaration of ‘aaa’ [-Wimplicit-int]
../List2.c:3:1: warning: type defaults to ‘int’ in declaration of ‘bbb’ [-Wimplicit-int]
bbb,
^
../List2.c:4:1: warning: type defaults to ‘int’ in declaration of ‘ccc’ [-Wimplicit-int]
ccc,
^
../List2.c:4:1: error: expected identifier or ‘(’ at end of input
make: *** [List2.o] Error 1
歡迎交流,分享。