字符串数组用头文件初始化,enum包含头文件

 比较适用于大量参数的数组,下标获取值(提升代码效率)

两个头文件:

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

欢迎交流,分享。

 

posted @ 2016-12-22 19:29  c_sun_boke  阅读(1980)  评论(0编辑  收藏  举报