【问题标题】:Flex compiling errorFlex 编译错误
【发布时间】:2012-10-21 18:00:34
【问题描述】:

我试图描述玩具语言的语法。这里是tokens.lex的内容:

/* Simple scanner for a toy language */

%{
/* need this for the call to atof() below */
#include <string.h>
#include <math.h>
%}

IDENTIFIER [a-z][a-z0-9]*
DIGIT      [0-9]

%%
{DIGIT}+ {
  printf("int: %s (%d)\n", yytext, atoi(yytext));
  yylval.string = new std::string(yytext, yyleng);
} /* define int type */

{DIGIT}+"."{DIGIT}+ {
  printf("float: %s (%d)\n", yytext, atof(yytext));
  yylval.string = new std::string(yytext, yyleng);
} /* define float type */

b[\'\"]{IDENTIFIER}[\'\"] {
  printf("bstream: %s\n", yytext);
  yylval.string = new std::string(yytext, yyleng);
} /* define bstream type */

u[\'\"]{IDENTIFIER}[\'\"] {
  printf("ustream: %s\n", yytext);
  yylval.string = new std::string(yytext, yyleng);
} /* define ustream type */

if|then|begin|end|procedure|function {
  printf( "A keyword: %s\n", yytext );
}

{IDENTIFIER}      printf( "identifier: %s\n", yytext );

"+"|"-"|"*"|"/"   printf( "operator: %s\n", yytext );

"{"[^}\n]*"}"     /* Remove one-line comments */

[ \t\n]+          /* Remove whitespace */

.                 printf( "Unrecognized character: %s\n", yytext );

%%
int argc;
char **argv;
int main(argc, argv);
  {
  if ( argc > 0 )
    yyin = fopen( argv[0], "r" );
  else
    yyin = stdin;
  yylex();
  }

然后我尝试编译它:

lex tokens.lex &amp;&amp; g++ -lfl lex.yy.c

编译器返回几个错误:

tokens.lex:51:20: error: expression list treated as compound expression in initializer [-fpermissive]
tokens.lex:51:20: error: invalid conversion from ‘char**’ to ‘int’ [-fpermissive]
tokens.lex:52:3: error: expected unqualified-id before ‘{’ token

这里有什么问题?我在 C/C++ 方面不是很强,所以我不知道这里发生了什么。请问你能帮帮我吗?谢谢!

【问题讨论】:

  • 也许你需要告诉 flex(1) 生成 C++? flex -+ ...

标签: compiler-construction compiler-errors lex flex-lexer


【解决方案1】:

main函数的正确写法是:

int main(int argc, char** argv)
{
  if (argc > 1)
    yyin = fopen(argv[1], "r");
  else
    yyin = stdin;
  return yylex();
}
  1. 参数类型应放在参数名称之前
  2. argv 数组的元素 [0] 是程序名称本身。真正的论点从 [1] 开始。

【讨论】:

  • g++ 告诉:/tmp/ccLObecG.o:在函数 main': lex.yy.c:(.text+0x1e32): multiple definition of main'/usr/lib64/gcc/x86_64-suse-linux/4.7/../../../ 中。 ./lib64/libfl.a(libfl_a-libmain.o):/home/abuild/rpmbuild/BUILD/flex-2.5.35/libmain.c:29: 这里首先定义/usr/lib64/gcc/x86_64-suse- linux/4.7/../../../../lib64/libfl.a(libfl_a-libmain.o):在函数main': libmain.c:(.text.startup+0xb): undefined reference to yylex'collect2:错误:ld返回1退出状态
  • @ghostmansd:链接时顺序很重要。请参阅stackoverflow.com/questions/1095298/… 以获得解释(这里您需要“yylex”,它在“libfl”中提供)。
  • 其实,有一件事你没有注意到。块前有一个分号。这就是编译器所抱怨的。
【解决方案2】:

您的 main() 参数声明是不正确的“C”语法,如另一个答案中所述,但无论如何这都是错误的。您的词法分析器必须返回标记,而不仅仅是打印它们。 lex/flex 的 main() 函数必须调用 yylex() 直到它返回零或 -1 或任何 EOS 指示。这就是 lex 库中的那个。

【讨论】:

    猜你喜欢
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    相关资源
    最近更新 更多