I have a YACC (Bison) grammar, a Lex (Flex) tokenizer, and a C program among which I need to share a struct (or really any variable). Currently, I declare the actual object in the grammar file and extern it wherever I need it (which is to say, my C source file), usually using a pointer to manipulate it. I have a shared header (and implementation) file between the C file and the grammar file with functions useful for manipulating my data structure. This works, but it feels a little uncomfortable. Is there a better way to share memory between the grammar and program?
I have a YACC (Bison) grammar, a Lex (Flex) tokenizer, and a C program
Share
A header file to share the extern declaration between the source files that need it is the best way to go, usually. The major alternative is to provide ‘functional access’ to it – that is, some sort of ‘get value’ and ‘set value’ function (or a set of functions). This is usually overkill. Ensure you include the header in the grammar (where you define the variable) as well as in the lexer and the other code so that inconsistencies are spotted as soon as possible.