How can I define two global `const` variables to the same value in a C module?

落花浮王杯 提交于 2019-12-11 13:24:04

问题


I’m using a pair of global variables in one of my .c files, matched to a single extern declaration each in two different .h files (well, one .h file, preprocessed two ways). One is for public consumption, and one is for private use. Both are const variables.

I only want to initialize one of the variables in my .c file, and then assign the second variable to the same content. Here’s the relevant contents of the .c file at the moment:

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

… and the corresponding .h:

#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

The goal here, is to ensure that when the .h is included with EXTERNALIZE defined, the including file gains access to the Paws__List variable, extern’d to the definition in my .c file. However, if it’s included without that definition, they gain access to an extern’d List instead (which I intend to use in my internal files, and make available if the #includeer wants it).

However, the Paws__List = List assignment blows up in my compiler, with the following error:

Source/Paws.o/list/list.c:32:40: error: initializer element is not a
      compile-time constant
struct List_methods const Paws__List = List;
                                       ^~~~

I’m looking for any help I can get to make this work as described above (that is, to define two const names for the same struct in my .c file, such that one or the other can be referenced by the .h header.)


回答1:


If i understand you correctly, you want to define an interface (vtable) and the implementation will vary depending on EXTERNALIZE:

I'd go that route:


/* 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

The important thing is that the structures are of the same type else you cannot assign one to the other. Second I would't override a symbol with an alias. This only makes problems when you want to use both for example in your .c file.



来源:https://stackoverflow.com/questions/2205579/how-can-i-define-two-global-const-variables-to-the-same-value-in-a-c-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!