Tomás Ó hÉilidhe wrote:
I have a translation unit which defines a global object:
BEGIN "yellow.c"
int i = 7;
END
I want this object to be accessible from other translation units, so I give
it external linkage. However I want it to be read-only in other translation
units. I didn't think it was too far-fetch to simply declare it as follows
in a header file:
BEGIN "yellow.h"
extern int const i;
END
Is this definitely not supported by C89? I realise I could write a function
which would return the variable's value, but I thought a solution like
above would be neater.
You'll probably get away with it, but I see two problems
(others may see more):
- You'll be unable to #include "yellow.h" in the compilation
of yellow.c, because the const and non-const declarations
conflict. This isn't fatal, but it means the compiler
never gets a chance to detect other mismatches between
the declarations in the header and the definitions in the
.c file -- change `int' to `long' in just one place, for
example, and the compiler won't be able to warn you.
- Nothing prevents an "outsider" from writing his own
`extern int i;' declaration or from setting up a pointer
with `int *pi = (int*)&i;', and mucking with the value
of `i' to his heart's content. This, too, is non-fatal
under the assumption of "cooperative" outsiders, but the
protection given by `const' is merely advisory if the
actual object has external linkage and isn't really `const'.
For greater cleanliness and greater protection, if you need
either, use an accessor function. If you don't like the syntax,
you can disguise it with a macro:
/* yellow.c */
static int i;
int geti(void) { return i; }
/* yellow.h */
int geti(void);
#define i ( geti() )
.... although indiscriminate use of this tactic can make garbage
out of otherwise clean code.
--
Eric Sosman
es*****@ieee-dot-org.invalid