Connecting Tech Pros Worldwide Forums | Help | Site Map

flex and C++

Newbie
 
Join Date: Mar 2007
Posts: 2
#1: Mar 24 '07
I was trying to get a simple program to work with flex and C++. I can't figure out what's wrong though. With C it works, and I can execute yyflex() with no problems and the analyzer gets executed. With C++ on the other hand...
Take a look:

Code
Expand|Select|Wrap|Line Numbers
  1. %option noyywrap yylineno c++
  2. %{
  3.         #include <iostream>
  4. %}
  5. %%
  6. "<"[A-Za-z]*">" { std::cout << YYText(); }
  7. %%
  8. int main () {
  9.     yylex();
  10.     return 0;
  11. }
Execution
Expand|Select|Wrap|Line Numbers
  1. $ flex test.l
  2. $ gcc -o test lex.yy.cc 
  3. test.l: In function 'int main()':
  4. test.l:10: error: 'yylex' was not declared in this scope



Expert
 
Join Date: Nov 2006
Location: UK
Posts: 1,320
#2: Mar 24 '07

re: flex and C++


C++ needs to know the function header (name, number and type of parameters) before it can call it otherwise it gives an error message such as the one you had (in C this not an error). possibly try adding the function prototype before main()
Expand|Select|Wrap|Line Numbers
  1.  void     yylex(void);
  2.  
Newbie
 
Join Date: Mar 2007
Posts: 2
#3: Mar 24 '07

re: flex and C++


The problem was that C++ needed a FlexLexer object, and then execute the yylex() function through it.

Like this:
Expand|Select|Wrap|Line Numbers
  1. int main() {
  2.         FlexLexer* lexer = new yyFlexLexer();
  3.         while (lexer->yylex() != 0)
  4.                 ;
  5.         return 0;
  6. }

Solved, thanks.
Reply