野牛弹性链接问题

Bison Flex linking problems

本文关键字:链接 问题      更新时间:2023-10-16

有一个解析器在bison&flex上运行。为了构建和制作整个项目,使用cmake。

因此,从flex文件创建词法分析器.cpp文件和bison文件解析器.cpp&parser.hpp。代码如下所示:

lexer.flex :

%{
#include "structures/RedirectionExpr.h"
// and about 8 includes like the upper one
#include <iostream>
#include <bits/stdc++.h>
#include "parcer.hpp"
using namespace std;
%}
%option noyywrap
%option c++
%%
/* Some staff */
%%

解析器.ypp :

%{
#include "structures/RedirectionExpr.h"
// and about 8 includes like the upper one, like in lexer.flex
#include <bits/stdc++.h>
#include <iostream>
extern "C" int yylex(void);
extern "C" int yyparse();
extern "C" int errors;
void yyerror (char const *s);
using namespace std;
%}
%union {
/* Union types. */ 
}
// %token definitions
// %type definitions for grammar
%%
/* grammar is here */
%%
void yyerror (char const *s) { /* Some code here */ }
int main(int argc, char *argv[])
{
do {
yyparse();
} while (true);
return 0;
}

在编译之前,我从.flex.ypp文件手动创建 cpp 文件:

flex -o lexer.cpp lexer.flex

Bison -d -o parser.cpp parser.ypp

为了构建所有这些混乱,我使用 cmake:

CMakeList.txt

cmake_minimum_required(VERSION 3.10)
project(parse)
set(CMAKE_CXX_STANDARD 14)
add_executable(parse 
src/structures/RedirectionExpr.cpp        
# other includes of classes used
src/lexer.cpp
src/parser.cpp src/parser.hpp
)

因此,链接时出现问题:

/usr/sbin/ld: CMakeFiles/parse.dir/src/parser.cpp.o: in function `yyparse':
parser.cpp:(.text+0x31a): undefined reference to `yylex'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/parse.dir/build.make:294: parse] Error 1
make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/parse.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

作为解决方案,我尝试添加%noyywrap选项,在包含其他类之后.flexparser.hpp包含在文件中,将extern "C" int yylex(void);行放入parser.ypp等。但是现在我不知道如何解决它。你能帮我吗?

更新

我通过删除extern "C"并将int yylex(void);部分保留在文件中parser.ypp解决了这个问题。您可以在此处阅读有关它的更多信息。

在我看来,你打算使用C词法分析器API。毕竟,在您的解析器中,您说

extern "C" int yylex(void);

因此,在 flex 文件中使用%option c++有点令人费解。如果这样做,您将获得C++接口,其中不包括"C"yylex()

我认为您简单的选择是删除该%option并将yylex声明更改为仅

int yylex();

没有extern "C"

如果你真的想使用C++接口,我相信Bison手册包括一个使用C++ flex词法分析器的例子。这是更多的工作,但我相信它会得到回报。

另外,我不是CMake用户,但我很确定CMake确实知道如何编译flex/bison项目(例如,请参阅此答案(。它可能会被C++接口混淆,但看起来做传统的 C 构建很容易。