build error : undefined reference to `yyFlexLexer::yyFlexLexer(std::istream*, std::ostream*)

build error : undefined reference to `yyFlexLexer::yyFlexLexer(std::istream*, std::ostream*)

我在 windows 机器上的应用程序中使用了 Flex,编译器是 mingw32-make。我的 C++ 代码出现构建错误。

我已经安装了 Flex,并且在 PATH 上完成了包含和 lib 目录的路由。
代码行是:

const char * filename;

std::fstream file;

file.open(filename, std::ios_base::in);

yyFlexLexer * scanner;

scanner = new yyFlexLexer(&file);

错误是:

"File.cpp:63: undefined reference to `yyFlexLexer::yyFlexLexer(std::istream*, std::ostream*)'"

请帮我解决这个问题。

提前致谢!

File.cpp:63: undefined reference to `yyFlexLexer::yyFlexLexer(std::istream*, std::ostream*)

这意味着您的 C++ 词法分析器未定义,或者以不同的名称定义。

如果不编译和 linking flex 文件,您将无法编写以下内容:

#include <fstream>
#include <FlexLexer.h>
int main()
{
  const char * filename= "file.txt";;
  std::fstream file;
  file.open(filename, std::ios_base::in);

  // better use auto scanner = std::make_unique<yyFlexLexer>(&file)
  yyFlexLexer * scanner; 
  // leaks memory
  scanner = new yyFlexLexer(&file);
}

如果不编写 flex 文件 运行 flex(默认生成 lex.yy.cc),然后编译并 linking 生成的代码,上述内容将无法工作。您可以在 Generating C++ Scanners.

中阅读所有相关信息

如果您编译并 link 生成的代码,如果创建了命名扫描器,您仍然可能会遇到此错误。基本上,如果您的程序有多个扫描仪,则为不同的扫描仪指定不同的名称是正确的解决方案。在这种情况下,您需要访问正确的名称。

这都在 flex 手册的 Generating C++ Scanners 部分。我在这里引用:

If you want to create multiple (different) lexer classes, you use the `-P' flag (or the `prefix=' option) to rename each yyFlexLexer to some other xxFlexLexer. You then can include `<FlexLexer.h>' in your other sources once per lexer class, first renaming yyFlexLexer as follows:

#undef yyFlexLexer 
#define yyFlexLexer xxFlexLexer 
#include <FlexLexer.h> 

#undef yyFlexLexer   
#define yyFlexLexer zzFlexLexer   
#include <FlexLexer.h> 

if, for example, you used `%option prefix="xx"' for one of your scanners and `%option prefix="zz"' for the other.

这很丑陋而且很棘手,但这是 flex 与 C++ 一起工作的方式。自 90 年代或更早以来,这已被记录为实验性的。我假设它不会改变。