2016-03-15 30 views
-1

我需要在我的C项目中存储关键字。现在,我不得不写保持const数据在一个地方

const char firstThingKeyword[] = "foofoofoofoo" 
const char secondThingKeyword[] = "barbarbarbar" 

的名字很长,所以我宁愿引用它们

keywords.firstThing 

有没有办法用标准C做到这一点? (可能是GCC扩展)

我想过使用一个结构体,但是我没有做任何事情,离开了C++舒适区。

+1

使用结构?既然这些是常量,那么最好使用'#define'? – Evert

+0

@Evert我想过struct,但只用C++编程(不是C)对我来说有点麻烦;) – marmistrz

+2

呃,是不是'keywords.firstThing'长于'firstThingKeyword'?如果这需要多长时间才能有明确的含义,那么将它们缩短会使它们变得不那么清晰。 – GManNickG

回答

3

这里是如何做到这一点使用struct一个简单的例子:

#include <stdio.h> 
#include <stdlib.h> 

struct _keywords { 
    const char *first; 
    const char *second; 
}; 

const struct _keywords Keywords = { 
    .first = "AAA", 
    .second = "BBB" 
}; 

int main(void) { 

    printf("first: %s\n", Keywords.first); 
    printf("second: %s\n", Keywords.second); 

    return 0; 
} 
+0

我怀疑'struct'也应该是'const'。全大写的名称只能用于宏或枚举常量。 – Olaf

+0

@Olaf好的建议,我编辑了这个片段 – thelaws

相关问题