Flex with C ++ getting started example

Source: Internet
Author: User
Tags lexer
Flex with C ++ getting started example
Anyone who has learned how to compile is probably familiar with Flex.
Flex-fast lexical analyzer generator is defined by GNU. It means Flex is fast Lex, but is it better than at&t's Lex? I don't know.

First, let's start with our first example. We need to count the number of lines and characters in a document. But I don't want to write the function myself. Well, let flex help me write it.

This is an example of C ++, which can be easily found online. C ++ is a little troublesome. Even if Flex is the latest version, C ++ standrad is still being developed when it is released. Therefore, due to the namespace STD problem, compilation may encounter some troubles.

First, use acmkdir to create a directory named test and acmkdir. For more information, see my previous article "develop C ++ applications with GNU Development Tool Kit" (http://www.blogcn.com/User5/snnn/blog/4919807.html ).

Then write test. l in the src directory.
% {

Int num_lines = 0, num_chars = 0;
%}
%

/N ++ num_lines; ++ num_chars;

. ++ Num_chars;

%

This file is divided into three parts.

The preceding variables in the C/C ++ format are included in % {and %}, or are directly "# include" something"

The middle two % And % are schema definitions. The regular expression is used to match the pattern on the left. If they match, the Statement on the right is executed.

Finally, you can write your own C/C ++ functions after %. For example, you can put a main (){}

Then use flex to generate

Flex-+ test. L
Note that the parameter-+ indicates generating the source file (lex. yy. CC) in C ++ format, instead of the C file (lex. yy. C)

I found a dead slave to help me write code,
How about a cup of coffee?
Forget it. When I got up, I found that it only took several MS to generate a 31734-byte source file. If this file was to be written by myself...
Do you want to open Lex. yy. CC?
For more than 1500 rows, forget it. Believe it, it will not make mistakes.

Create a CPP file. This is my test. cpp file.
More test. cpp
/*! /File test. cpp
*/Brief test. cpp
*/Date 30 Nov 2004 22:05:31
*/Author snnn119@hotmail.com
*/

/*
** Copyright (c) 2004 cyper sun <snnn119@hotmail.com>
**
** This program is free software; you can redistribute it and/or modify
** It under the terms of the GNU General Public License as published
** The Free Software Foundation; either version 2 of the license, or
** (At your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** But without any warranty; without even the implied warranty
** Merchantability or fitness for a special purpose. See
** GNU General Public License for more details.
**
**
**
*/
# If have_config_h
# Include <config. h>
# Endif

# Include <flexlexer. h>
# Include <fstream. h>

Extern int num_lines, num_chars;

Int main (INT argc, char ** argv ){
If (argc = 1 ){
Printf ("Usage: % s", argv [0]);
Return 1;
}
Ifstream * pmyfile = new ifstream ();
Pmyfile-> open (argv [1], IOS: Out );
If (pmyfile-> fail ()){
Printf ("error while open the file ";
Return 1;
}
Flexlexer * lexer = new yyflexlexer (pmyfile );
While (lexer-> yylex ()! = 0 );
Printf ("Total lines: % d/ntotal chars: % d/N", num_lines, num_chars );
Delete pmyfile;
Delete lexer;
Return 0;
}

Note that yyflexlexer is a derived class from flexlexer. Flexlexer is an abstract base class defined in <flexlexer. h>.
Below I will briefly introduce these two classes
Bytes ------------------------------------------------------------------------------------------------------------------
Class flexlexer:
This is an abstract class
Const char * yytext ()
Returns the text of the most recently matched token, the equiva-
Lent of yytext.
Returns the last match, in the same format as yytext in C.

Int yyleng ()
Returns the length of the most recently matched token,
Equivalent of yyleng.
Returns the length of the last match, in the same format as yyleng in C.

Int lineno () const
Returns the current input line number (see % option yylineno), or
1 If % option yylineno was not used.
Returns the row number of the last match, or 1 If you disable this option in option. Yylineno in the same C format

There are also some member functions such:
Yy_create_buffer (), yy_flush_buffer (), yy_delete_buffer (), yyrestart (), and so on. For specific usage, read the source code. (Sorry, there is no doc any more ).
Bytes ------------------------------------------------------------------------------------------------------------------
Class yyflexlexer:
Inherited from flexlexer
Yyflexlexer (istream * arg_yyin = 0, ostream * arg_yyout = 0
This is its constructor. It uses an iistream * arg_yyin instead of the previous yyin for input and ostream * arg_yyout for output. That is to say, its input and output can also be varied, such as files and CIN.
If this parameter is not specified, the default input and output streams are CIN and cout.

Virtual int yylex ()
Analyze the input, which is defined in <flexlexer. h> and implemented in lex. yy. CC.

Virtual void lexeroutput (const char * Buf, int size
Write the size bytes in the Buf to the output stream.

For other functions, see <flexlexer. h>
Bytes ------------------------------------------------------------------------------------------------------------------

Okay, modify src/makefile. am to tell it what to compile.
Bin_programs = test
Test_sources = test. CPP/
Lex. yy. CC

Include = (all_include)
Test_ldflags = (all_libraries)

Then Configure. AC is used to check whether flex/lex exists on the target machine.
Add only one row
Ac_prog_lex

OK, compile
In theory, this is enough, but it cannot be passed on my machine. My GCC 3.4 is broken. What I use now is
GCC -- version
GCC (GCC) 3.3.1 (cygming Special)
It prompts the istream redefinition

You can find the Forward Declaration of istream in lex. yy. CC and replace it with # include <istream. h>

Then compile and run,
./Test. L
Total lines: 25
Total chars: 145

Note: it is a bad habit to name a program "test" because a system tool named test already exists on UNIX/Linx systems.

If you want to query the number of occurrences of a specific mode (such as email address and tag) in a file, just change the two regular expressions in test. L.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.