build error : undefined reference to `yyFlexLexer::yyFlexLex

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

本文关键字:yyFlexLexer to yyFlexLex reference error undefined build      更新时间:2023-10-16

我在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++ 词法分析器要么未定义,要么以不同的名称定义。

如果不编译和链接 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(,然后编译和链接生成的代码,上述内容将不起作用。您可以在生成C++扫描仪中阅读所有相关信息。

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

这一切都在 flex 手册的生成C++扫描仪部分。我在这里引用:

如果要创建多个(不同的(词法分析器类,请使用 "-P"标志(或"前缀="选项(将每个 yyFlexLexer 重命名为 其他一些 xxFlexLexer。然后,>

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

例如,如果您将"%选项前缀="xx"用于您的之一 扫描仪和"%选项前缀="zz"表示另一个。

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