簡體   English   中英

Bison Flex 鏈接問題

[英]Bison Flex linking problems

有一個解析器在bison & flex上運行。 使用 cmake 來構建和制作整個項目。

所以,從 flex 文件我創建lexer.cpp文件和野牛文件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 */
%%

解析器.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);解決了這個問題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 構建。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM