字符串数组用头文件初始化,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

欢迎交流,分享。

原文链接: https://www.cnblogs.com/csun/p/6212571.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/246281

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午1:25
下一篇 2023年2月14日 上午1:26

相关推荐