How to share compile time generated enumerations in C?
In a simple example, I have two source files...one using a particular
string, like this:
main.c
#include <stdio.h>
#include "stringdata.h"
int main(int argc, char *argv[])
{
print_somestring(thestring, (enum strsizes)stringlen);
return 0;
}
Then this:
stringdata.c
const unsigned char thestring[] = "This is a string\n";
enum strsizes
{
stringlen = sizeof(thestring) - 1 //to account for the null byte
};
The header for main:
stringdata.h
extern const unsigned char thestring[];
extern enum strsizes; //<-- how?
Now, I've tried to compile that and I got what I expected...it doesn't
like it. The major issue is being able to have the enum "see" the actual
defined strings so that sizeof evaluates properly; the extern symbol alone
doesn't give sizeof enough information, thus I'd have to declare and
initialize the strings in every compilation unit, which would obviously
break.
I understand that normally, you'd define the enum type in the header, and
then use the constants where you need them. In this case, the value of the
constants depend on compile time conditions (the evaluated "byte" size of
the string).
In order to use those constants in other compilation units, I'd need the
enum type definition to "stick", if you will. Obviously, an extern won't
do it. Making the constants take up actual storage by using a real type i.
e. const int is what I want to avoid.
I've tried for quite a while to look up examples, but none of them seem to
be what I'm looking for. The solutions I have found involve C++ Template
Meta Programming, but I'm strictly using C.
If anyone could help me out, thanks well in advance (this will have other
very beneficial effects on my project).
No comments:
Post a Comment