Yacc error: undefined reference to `line_num'

Yacc error: undefined reference to `line_num'

我被指派用 lex 和 yacc 实现一种新的编程语言。下面是我的一些 yacc 代码,它应该打印错误并且发生行错误

//rest of the code
%%
#include "lex.yy.c"
extern int line_num;

main() {
  return yyparse();
}
void yyerror( char *s )
{   
    fprintf(stderr,"Syntax Error in line: %d\n%s\n",line_num, s);
}

编译器给出以下错误信息:

/tmp/cclW8fn4.o: In function `yyerror':
y.tab.c:(.text+0x200f): undefined reference to `line_num'
collect2: error: ld returned 1 exit status
make: *** [all] Error 1

如何解决?

正如评论中讨论的那样 extern int line_num; 只是声明 line_num,它必须存在于另一个文件中。

因此在 lex 文件中声明 int line_num 时问题得到解决:

%{
   int line_num = 1;    
%}