简体   繁体   English

将C Flex lexer链接到C ++解析器

[英]Link C Flex lexer to C++ parser

I am using Flex to develop a lexer for a language of mine. 我正在使用Flex为我的语言开发词法分析器。 I want to create the parser in C++ and I am using my own approach for it. 我想用C ++创建解析器,我正在使用自己的方法。 Since the lexer is in C (Flex), I want to compile the lexer ( gcc -c lex.yy.c -lfl ) and my program ( g++ -c file1.cc file2.cc ... ) separately and then link them together to create the final executable. 由于词法分析器在C(Flex)中,我想分别编译词法分析器( gcc -c lex.yy.c -lfl )和我的程序( g++ -c file1.cc file2.cc ... ),然后将它们链接起来一起创建最终的可执行文件。

In particular, after creating the lexer, I write the following code for my C++ program: 特别是在创建词法分析器之后,我为我的C ++程序编写了以下代码:

#include <iostream>

extern int yylex();
int main(int argc, char** argv);

int main (int argc, char** argv) {
  yylex();
  return 0;
}

But I get link error when I link stuff together like: 但是当我把东西链接在一起时,我得到链接错误,如:

g++ main.cc lex.yy.o -lfl

But I always get: 但我总是得到:

/tmp/ccBrHObp.o: In function `main':
main.cc:(.text+0x10): undefined reference to `yylex()'
collect2: ld returned 1 exit status

Where is the problem? 问题出在哪儿? Thankyou 谢谢

What happens here is that you compile the C code, which is something like this: 这里发生的是你编译C代码,它是这样的:

int yylex() {
  // ...
}

It generates a yylex symbol. 它会生成一个yylex符号。 Then you compile the C++ code. 然后编译C ++代码。 As C++ allows two different functions with the same name to exist, it can't just use the name of the function as the symbol name. 由于C ++允许存在两个具有相同名称的不同函数,因此它不能仅使用函数的名称作为符号名称。 When you write int yylex(); 当你写int yylex(); on C++ code, GCC looks for this symbol: _Z5yylexv . 在C ++代码中,GCC查找此符号: _Z5yylexv It doesn't find, link error. 它找不到,链接错误。 The solution is to say that this is a C function and we should use its name as symbol name: 解决方案是说这是一个C函数,我们应该使用它的名称作为符号名称:

#include <iostream>

extern "C"
int yylex();

int main (int argc, char** argv) {
  std::cout << yylex() << std::endl;
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM