如何在C模块中将两个全局`const`变量定义为相同的值?

时间:2010-02-05 07:14:50

标签: c const global-variables extern

我在我的.c个文件中使用了一对全局变量,与两个不同extern文件中的单个.h声明匹配(嗯,一个{{1}文件,预处理两种方式)。一个用于公共消费,一个用于私人用途。两者都是.h变量。

我只想初始化我的const文件中的一个变量,然后将第二个变量分配给相同的内容。以下是.c文件的相关内容:

.c

......和相应的.h:

struct List_methods const List = {
  .create         = List__create,
  .create_naughty = List__create_naughty,
  // …
};
struct List_methods const Paws__List = List;

此处的目标是确保在定义#if defined(EXTERNALIZE) # define List_methods Paws__List_methods # define List Paws__List #endif // … struct List_methods { list (*create) (void); list (*create_naughty) (void); // … } const extern List; #if defined(EXTERNALIZE) # undef List_methods Paws__List_methods # undef List Paws__List #endif .h包含时,包含文件可以访问EXTERNALIZE变量,Paws__List'd我的extern文件中的定义。但是,如果它包含没有该定义,则可以访问.c'd extern(我打算在我的内部文件中使用它,如果List呃想要它。)

但是,#include赋值在我的编译器中爆炸,出现以下错误:

Paws__List = List

我正在寻找可以帮助我完成上述工作的任何帮助(也就是说,在我的Source/Paws.o/list/list.c:32:40: error: initializer element is not a compile-time constant struct List_methods const Paws__List = List; ^~~~ 文件中为同一个结构定义两个const名称,例如另一个可以通过.c标头引用。)

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你想要定义一个接口(vtable),实现将根据EXTERNALIZE而变化:

我会走这条路:


/* header file */
/* define the interface */
typedef struct List_methods {
  list  (*create)         (void);
  list  (*create_naughty) (void);
  // …
} List_Methods;

const extern List_methods Paws_List; // note: double underscores are afaik not allowed
const extern List_methods Other_List; // take any name but List

#ifdef EXTERNALIZE
# define  List          Paws_List
#else
# define  List          Other_List
#end

重要的是,结构属于同一类型,否则你无法分配一个 其他。其次,我不会覆盖带别名的符号。如果要在.c文件中同时使用这两种方法,这只会产生问题。