Akshit Kansra
Akshit Kansra

Reputation: 11

Using C++ Code in yacc file

I have an assignment to make, where I have to parse a circuit code to render the SVG of the circuit using flex and bison. I want to use C++ STL to make my life easier, but have been unable to do so. Here is my code:

Sample.y

%{
void yyerror (char *s);     /* C declarations used in actions */
#include <stdio.h>
#include <stdlib.h>
%}

.
.
..tokens and grammer....
.
.

int main (void) 
{
    /* init symbol table */
    return yyparse ( );
}

void yyerror (char *s) {fprintf (stderr, "%s\n", s);} 

scan.l

%{
#include "Sample.tab.h"
%}
%%
.
.
lexical rules
.
.
%%
int yywrap (void) {return 1;}

I have tried many approaches like using extern "C", including yylex(),yyparse etc, but it didn't work. How exactly can I make C++ code work in yacc file? I also know there is an approach where we can make a third 'main.cpp' file and code in that. How exactly will that approach work? Kindly tell what changes do I need to make to my code to make it work. The file works perfectly with C, but cannot use cout, cin etc in this.

Upvotes: 1

Views: 3369

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25266

After the first (or every) %{ you specify the

#if defined(__cplusplus)
extern "C" {
#endif

and before every %} you specify the

#if defined(__cplusplus)
}
#endif

If you run yacc and open the generated C file, you see that yacc includes your C or C++ code verbatim (with $ variables replaced with yacc stack indexes) and includes a basic parser. If you add the C++ directives around it, it will compile as C++. You may also need to adapt file yaccpar, which contains the parser template into which yacc inserts its code.

If this doesn't help, you can manually adapt the generated C file: open it and put extern "C" { on line 1 and a } on the last line.

Upvotes: 2

Related Questions