A
Anders Wegge Keller
When writing modular code, I sometimes want to make a particular data
structure read-only outside the module that need to write to it. The
most obvious example is global options, that is only written to by the
command-line parsing module, and should be const elsewhe. However,
getting this declaration to change depending on where it's seen
becomes a bit unsightly, so I wonder if there is a better way of doing
this:
<<options.h>>
....
typedef struct {
int option_1;
int option_2;
...
int option_N;
} Options_t;
#ifdef OPTION_RW
extern Options_t *options;
#else
extern const Options_t * const options;
#endif
<<options.c>>
#define OPTIONS_RW
#include <options.h>
#undefine OPTIONS_RW
....
options = malloc (sizeof Options_t);
....
What I'd like to do is getting rid of the OPTIONS_RW definition in
options.c. Creating two extra header files (options_public.h and
options_private.h), and keeping the declaration in those two isn't an
improvement - in my opinion - on the definition above.
structure read-only outside the module that need to write to it. The
most obvious example is global options, that is only written to by the
command-line parsing module, and should be const elsewhe. However,
getting this declaration to change depending on where it's seen
becomes a bit unsightly, so I wonder if there is a better way of doing
this:
<<options.h>>
....
typedef struct {
int option_1;
int option_2;
...
int option_N;
} Options_t;
#ifdef OPTION_RW
extern Options_t *options;
#else
extern const Options_t * const options;
#endif
<<options.c>>
#define OPTIONS_RW
#include <options.h>
#undefine OPTIONS_RW
....
options = malloc (sizeof Options_t);
....
What I'd like to do is getting rid of the OPTIONS_RW definition in
options.c. Creating two extra header files (options_public.h and
options_private.h), and keeping the declaration in those two isn't an
improvement - in my opinion - on the definition above.