title: Using Lex Yacc compiled .c file in C++
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/526797/good-tools-for-creating-a-c-c-parser-analyzer">Good tools for creating a C/C++ parser/analyzer</a><br>
    <a href="https://stackoverflow.com/questions/780676/string-input-to-flex-lexer">String input to flex lexer</a>  </p>
  </blockquote>
  
  
  
  <p>My idea is to create a parser that can calculate the expression of Boolean, and my next step is to use it in my c++ program, but I don't know how to use it. </p>
  
  <p>Currently, this calculator can run in command line, the code is not good, and I don't know how to use it in my program. I want to use a function <code>lex_yacc(var)</code> to call this calculator, and <code>var</code> is the input, for example, the main program read the <code>var</code> is <code>(T+F)</code>， so it will be sent to <code>lex_yacc(var)</code>, finally, the func returns <code>1</code>. </p>
  
  <p>I define the lexya.l as follows:  </p>
  
  <pre><code>%{
  
  #include &lt;stdlib.h&gt;
  
  void yyerror(char *);
  
  #include "lexya_a1.tab.h"
  %}
  
  %%
  
  "T"       { yylval = 1; return boolean; }
  "F"       { yylval = 0; return boolean; }
  "!F"      { yylval = 1; return boolean; }
  "!T"      { yylval = 0; return boolean; }
  
  [+*\n]     return *yytext;
  "("        return *yytext;
   ")"       return *yytext;
  [\t]       ;/* .... */
  
  .            yyerror("....");
  
  %%
  
  int yywrap(void) {
       return 1;
  }
  </code></pre>
  
  <p>And lexya_a1.y:</p>
  
  <pre><code>%{
  #include &lt;stdlib.h&gt;
  
  int yylex(void);
  
  void yyerror(char *);
  
  %}
  
  %token boolean
  
  %left '+' '-'
  
  %left '*'
  
  %left '(' ')'
  
  %%
  
  program:
      program expr '\n' { printf("%d\n", $2); }
    |
    ;
  
  expr:
      boolean { $$ = $1; }
    | expr '*' expr { $$ = $1 * $3; }
    | expr '+' expr { $$ = $1 + $3; }
    | '(' expr ')' { $$ = $2; }
    ;
  
  %%
  
  void yyerror(char *s) {
       printf("%s\n", s);
  }
  
  int main(void) {
      yyparse();
      return 0;
  }
  </code></pre>