LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   How does a c program see the variable declared in a lex & yacc file (https://www.linuxquestions.org/questions/linux-general-1/how-does-a-c-program-see-the-variable-declared-in-a-lex-and-yacc-file-938772/)

carlnet 04-08-2012 01:49 PM

How does a c program see the variable declared in a lex & yacc file
 
Hi guys, I wrote a simple parser in lex and yacc and I have declared my data structure in there (namely, an array). When I am parsing a file, I store the data contained within the file in the array. Then I would like to print them out using a .c file. However, there is no header in lex and yacc for me the c file to see the array declared in the lex and yacc files. So how is it possible for me to use any of the variables declared in lex and yacc?

Dark_Helmet 04-08-2012 02:25 PM

For these kinds of questions, you will almost always get better responses if you include the code you're trying to use.

To include code in one of your messages, use code tags. For instance, typing this in your message:

[code]
#include <stdio.h>

int main( int argc, char *argv[] )
{ return 0; }
[/code]

Will produce:
Code:

#include <stdio.h>

int main( int argc, char *argv[] )
{ return 0; }

To your question...

If you want one C file to access a data structure instantiated in another C file, the simplest method is to:
1. declare the variable type using a typedef in a header file
2. #include the header with the definition in the file that wants to access the data and in the file that will populate the data structure with data
3. create an instance of the variable at a global scope (i.e. not inside a function) in the file that populates the data structure
4. create an instance of the variable by using the same name, but add "extern" before the type in the file that wants to access the data

Something like:

common.h
Code:

#ifndef __COMMON_H__
#define __COMMON_H__

typedef struct {
  int myInteger;
  double myDouble;
} myStructure;

#endif

file1.c
Code:

#include "common.h"

myStructure recordedData;

/* Code to populate recordedData */

file2.c
Code:

#include "common.h"

extern myStructure recordedData;

/* Code that accesses the information in recordedData */

The lex and yacc specifications include sections where you can insert C code that will be passed verbatim to the final generated code. You would place the #include and the recordedData declaration in that section.

Note: You should have only once C file that declares recordedData without the extern keyword. This means that if your data structure is being populated by both your lex specification and your yacc specification, one of them need to use the "extern" keyword.

Make sense?

pan64 04-11-2012 03:31 AM

man yacc has a simple example about the usage. what is the problem with that?


All times are GMT -5. The time now is 11:51 AM.