有一个解析器运行在bison & flex上。使用cmake来构建和制作整个项目。
因此,我从flex文件创建了lexer.cpp文件,并从bison文件创建了parser.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 */
%%parser.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
野牛-d -o parser.cpp parser.ypp
为了建立所有这些混乱,我使用cmake:
CMakeLists.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选项,将parser.hpp包含到.flex文件中,而不是包含其他类,将extern "C" int yylex(void);行放入parser.ypp等等。但是现在我不知道如何修复它。你能帮我吗?
更新
我通过删除extern "C"并将int yylex(void);部件留在parser.ypp文件中解决了这个问题。您可以阅读更多关于它的here。
发布于 2019-12-27 18:22:48
在我看来,您似乎打算使用C。毕竟,在解析器中,您会说
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项目(例如,参见this answer)。它可能会被C++接口搞混,但看起来很容易完成传统的C构建。
https://stackoverflow.com/questions/59503920
复制相似问题