0

我对 flex 完全陌生。

使用 flex 时出现构建错误。也就是说,我使用 flex 生成了一个 .c 文件,并且在运行它时,我收到了这个错误:

1>lextest.obj : error LNK2001: unresolved external symbol "int __cdecl isatty(int)" (?isatty@@YAHH@Z)
1>C:\...\lextest.exe : fatal error LNK1120: 1 unresolved externals

这是我正在使用的 lex 文件(从这里获取):

/*** Definition section ***/

%{
/* C code to be copied verbatim */
#include <stdio.h>
%}

/* This tells flex to read only one input file */
%option noyywrap


%%
    /*** Rules section ***/

    /* [0-9]+ matches a string of one or more digits */
[0-9]+  {
            /* yytext is a string containing the matched text. */
            printf("Saw an integer: %s\n", yytext);
        }

.       {   /* Ignore all other characters. */   }

%%
/*** C Code section ***/

int main(void)
{
    /* Call the lexer, then quit. */
    yylex();
    return 0;
}

同样,为什么我必须在 lex 语法代码中放置一个“主”函数?我想要的是能够调用 yylex(); 从另一个c文件。

4

2 回答 2

6

Q1 链接错误

看起来好像对 isatty() 函数有些困惑。它不会显示在您显示的代码中 - 但它可能会在 flex 生成的代码中被引用。如果是这样,您似乎正在使用 C++ 编译器进行编译,并且 isatty() 函数被视为具有 C++ 链接的函数并且没有被发现 - 它通常是具有 C 链接的函数,需要用' extern "C" int isatty(int);' 在 C++ 代码中。

要解决,请跟踪是否isatty()出现在生成的 C 中。如果是,还要跟踪它的声明位置(它的 POSIX 标准标头是<unistd.h>)。

Q2 主要

您不必将主程序放在带有词法分析器的文件中。实际上,您通常不会这样做,或者其中的主程序将只是一个用于单独测试词法分析器的虚拟程序(并且仅有条件地编译到代码中 - 内部#ifdef TEST / #endif或等效代码)。

是什么让你认为你必须这样做?

于 2010-04-14T06:09:28.270 回答
-1

链接错误看起来像是您尝试在 Windows 上使用非 Windows 原生版本的 flex,但它无法正常工作。如果使用cygwin自带的flex版本,需要用cygwin的编译器和链接器编译链接程序。

于 2010-04-14T06:22:19.517 回答