0

How can I resolve the "undefined reference to 'yylval'" error in the simplest program ever?

This is my lexer.l file

%{
    #include "parser.tab.h"
%}

%%
[0-9]+      {
                yylval = atoi(yytext);
                return NUMBER; }
"-"         {return MINUS;}

%%

int main ()
{
     yylex();
     return 0;
}

and this is my parser file

%{
#include <stdio.h>
#include <stdlib.h>

void yyerror(const char* msg); 
int n=0;
%}

%token MINUS 
%token NUMBER

%%

program :   NUMBER MINUS NUMBER { n=$1-$3 ; printf("%d\n",n);}

%%
void yyerror(const char* msg){
    printf("%s\n", msg); 
}

int main() {
    printf("Enter  ");
    yyparse();  // Start parsing
    return 0;
}

And these are the commands I run to build this program:

C:\Users\User\Desktop\workbench\prevodiocip\nnn>bison -d parser.y

C:\Users\User\Desktop\workbench\prevodiocip\nnn>flex lexer.l

C:\Users\User\Desktop\workbench\prevodiocip\nnn>gcc -o parser.tab.c lex.yy.c -lfl
C:\Users\User\AppData\Local\Temp\ccOvWXJo.o:lex.yy.c:(.text+0x1b1): undefined reference to `yylval'
collect2.exe: error: ld returned 1 exit status

I have tried everything, but nothing works for me.

8
  • 4
    With -o parser.tab.c you're saying that parser.tab.c should be the executable file, so you're overwriting the original. Commented Jun 22 at 4:17
  • @user207421: extern int is insufficient to create a proper definition (e.g., extern int yylval; is not a definition), and header files are generally inappropriate places to define objects. A definition should be placed in a C file, possibly YYSTYPE yylval; in modern versions of Bison. Commented Jun 22 at 9:18
  • 1
    You haven't compiled or linked parser.tab.c which contains the definition. You've tried to name it as the linker output file, which doesn't make any sense at all. NB (1) flexbox isn't for questions about flex(1): be accurate. (2) You don't need the definition for MINUS: does return ad use '-', which is simpler all round. Commented Jun 22 at 9:58
  • @EricPostpischil True, my bad. Commented Jun 22 at 9:59
  • Side note: you generally do not want to use libfl, except possibly in support of a program built entirely from a scanner definition. This library provides mainly a main() that you definitely do not want when driving the scanner from a separate parser, and a dummy-ish yywrap() that you would do better to obviate by adding %option noyywrap to your scanner definition. Commented Jun 22 at 13:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.