Lex and yacc windows

Как скомпилировать файлы LEX/YACC на Windows?

У меня есть файлы Lex и YACC для разбора моих файлов ( файл .l и файл .y ).

Как скомпилировать эти файлы и как сделать для них эквивалентный файл .c на платформе windows?

9 ответов

Как можно сделать комментарий в Lex и Yacc? До сих пор я не пробовал Yacc, но в Lex я пробовал /* comment */ и // comment , но ни один из них не компилируется. Я нахожусь на Mac, используя встроенные компиляторы Lex и Yacc (или, может быть, X-код, я не знаю). Каков правильный синтаксис.

Как скомпилировать их в ПК Windows 7? % lex chl-n.1 % yacc -d chl-m.y % cc -c 1ex.yy.c y.tab.c % cc -0 example-m.n 1ex.yy.o y.tab.0 -11 разве это так? flex my_code.l bison -y -d my_code.y gcc -c y.tab.c lex.yy.c gcc y.tab.o lex.yy.o my_code.c -o my_code.exe но мой последний код не работает, он.

На сегодняшний день (2011-04-05, обновлено 2017-11-29) вам понадобятся самые последние версии:

После этого выполните полную установку в каталог по вашему выбору без пробелов в имени . Я предлагаю C:\GnuWin32 . Не устанавливайте его по умолчанию (C:\Program Files (x86)\GnuWin32), потому что у bison есть проблемы с пробелами в именах каталогов, не говоря уже о скобках.

Кроме того, подумайте об установке Dev-CPP в каталог по умолчанию ( C:\Dev-Cpp )

После этого установите переменную PATH так, чтобы она включала каталоги bin gcc (в C:\Dev-Cpp\bin ) и flex\bison (в C:\GnuWin32\bin ).) для этого скопируйте следующее: ;C:\Dev-Cpp\bin;C:\GnuWin32\bin и добавьте его в конец переменной PATH , определенной в месте, показанном на этом рисунке:

Если рисунок не имеет хорошего разрешения, вы можете увидеть здесь step-by-step .

Откройте приглашение, компакт-диск в каталог, где находятся ваши «.l» и «.y», и скомпилируйте их с помощью:

  1. flex hello.l
  2. bison -dy hello.y
  3. gcc lex.yy.c y.tab.c -o hello.exe

Вы сможете запустить программу. Я сделал исходники для простого теста (печально известный Hello World ):

Hello.l

Hello.y

Отредактировано: избегая «warning: implicit definition of yyerror and yylex».

Отказ от ответственности: помните, что этот ответ очень стар (с 2011 года!), и если вы столкнетесь с проблемами из-за изменения версий и функций, вам может потребоваться больше исследований, потому что я не могу обновить этот ответ, чтобы отразить новые итены. Спасибо, и я надеюсь, что это будет хорошей отправной точкой для вас, как это было для многих.

Обновления: если что-то (действительно небольшие изменения) нужно сделать, пожалуйста, проверьте официальный репозиторий по адресу github: https://github.com/drbeco/hellex

То , что вы (вероятно, хотите), — это Flex 2.5.4 (некоторые люди сейчас «maintaining» it и выпускают более новые версии, но IMO они сделали больше, чтобы испортить его, чем исправить какие-либо реальные недостатки) и byacc 1.9 (аналогично). (Edit 2017-11-17: Flex 2.5.4 больше не доступен на Sourceforge, а репозиторий Flex github возвращается только к 2.5.5. Но вам видимо все равно можете получить это от гну сервер ftp на ftp://ftp.gnu.org/старый гну/гну-0.2/НИЦ/флекс-2.5.4.tar.gz .)

Поскольку это неизбежно будет рекомендовано, я предостерегу от использования бизона. Первоначально «Бизон» был написан Робертом Корбеттом, тем же парнем, который позже написал Byacc, и он открыто заявляет, что в то время он действительно не знал и не понимал, что делает. К сожалению, будучи молодым и глупым, он выпустил его под названием GPL, и теперь поклонники GPL толкают его как ответ на жизненные беды, хотя его собственный автор в основном говорит, что его следует рассматривать как продукт бета-тестирования-но по запутанным рассуждениям поклонников GPL, лицензия byacc не имеет достаточных ограничений, чтобы квалифицироваться как «free»!

Здесь есть порты flex и bison для windows: http:/ / gnuwin32.sourceforge.net/

Flex -это свободная реализация Лекс. зубр является свободная реализация yacc.

Нам нужно создать файл .c из файлов .l (lax) и .y (yacc), используя visual studio 1o на windows 2008. Мы вообще не можем использовать Cygwin. Где здесь появляются Флекс и бизон ? Даже Flex и Bison используют cygwin внутренне или нет ? как мы должны это делать ?

Читайте также:  Как установить windows ноутбук dns

Я пытаюсь скомпилировать свою программу, которая имеет файл lex, файл yacc и пару файлов C. Я наткнулся на этот пример в руководстве Flex . У меня есть пара вопросов относительно этого файла makefile. Он не указывает компилятор, такой как gcc откуда makefile знает, как создавать целевые объекты.

Вы можете найти последнюю версию flex & bison windows здесь: http://sourceforge.net/projects/winflexbison /

Перейдите к полной установке Git для windows (с помощью инструмента Unix), а bison и flex будут поставляться вместе с ним в папке bin .

Также стоит отметить, что WinFlexBison был упакован для менеджера пакетов Chocolatey. Установить и пройти:

. который на момент написания статьи содержит Bison 2.7 & Flex 2.6.3.

Существует также winflexbison3 , который (на момент написания статьи) имеет Bison 3.0.4 & Flex 2.6.3.

самый простой способ-загрузить и установить пакеты cygwin и gcc и flex во время установки. Затем запустить lex-файл для eg. abc.l

У меня была та же проблема, но она имеет очень простое решение.
Шаги для выполнения программы ‘Lex’:

  1. Tools->’Lex Компилятор Файлов’
  2. Tools->’Lex построить’
  3. Tools->’Open CMD’
  4. Затем в командной строке введите ‘name_of_file.exe’ example->’1.exe’
  5. Затем, введя весь ввод, нажмите Ctrl + Z и нажмите Enter.

Похожие вопросы:

Я работаю над новым языком программирования, но меня всегда озадачивал тот факт, что все используют yaxx/lex для разбора кода, а я-нет. Мой компилятор (который уже работает) закодирован вручную в.

Я пытаюсь скомпилировать несколько программ lex и yacc. В колледже мы используем Fedora Core 4. Я использую тот же OS на виртуальной машине дома, но не могу скомпилировать программу. Ниже приведены.

Как настроить lex и Yacc с помощью Xcode 4? Какой пользовательский скрипт я должен написать в правилах сборки, чтобы сделать это? У меня есть один файл lex abc.l и один файл yacc cba.y, оба помещены.

Как можно сделать комментарий в Lex и Yacc? До сих пор я не пробовал Yacc, но в Lex я пробовал /* comment */ и // comment , но ни один из них не компилируется. Я нахожусь на Mac, используя.

Как скомпилировать их в ПК Windows 7? % lex chl-n.1 % yacc -d chl-m.y % cc -c 1ex.yy.c y.tab.c % cc -0 example-m.n 1ex.yy.o y.tab.0 -11 разве это так? flex my_code.l bison -y -d my_code.y gcc -c.

Нам нужно создать файл .c из файлов .l (lax) и .y (yacc), используя visual studio 1o на windows 2008. Мы вообще не можем использовать Cygwin. Где здесь появляются Флекс и бизон ? Даже Flex и Bison.

Я пытаюсь скомпилировать свою программу, которая имеет файл lex, файл yacc и пару файлов C. Я наткнулся на этот пример в руководстве Flex . У меня есть пара вопросов относительно этого файла.

Я выполнил все шаги, описанные здесь: как скомпилировать файлы LEX/YACC на Windows? Но я получаю эту ошибку:

У меня есть проект lex/yacc, который прекрасно справляется с одной вещью. У меня есть еще один lex yacc, который отлично справляется с другой задачей . Основная часть этих yacc имеет указанный.

Известно, что PLY пытается достичь того, что Лекс и Yacc делают в Python. Мне было интересно, предоставляет ли библиотека метод для parse/translate/convert .l (файлы lex) или .y (файлы yacc) самих.

Life Of Navin

Random Musings, Random Bullshit.

LEX and YACC on Windows

We’ve just started compiler design as part of the Language Translators subject at college and a practical aspect of it involves using LEX and YACC for Grammar Lexical Analysis and Parser Generation. Since LEX and YACC are both originally developed for the *nix OSes ( read: Linux ), there was a sudden rush of classmates downloading linux distros (Fedora being the default choice as it’s used on lab systems ). In many cases, people actually downloaded entire distro DVDs just for LEX/YACC!

NOTE : When people say they use LEX and YACC , almost always, what they mean is FLEX (Which is an alternative to Lex) and BISON (which is part of the GNU project) / BYACC respectively.

Читайте также:  Dvd converter mac os

Sticking with the » When in doubt, try another hole » philosophy, I just googled around a little and came up with a much easier solution.


Here’s how to set up FLEX and BISON on Windows systems

1) Download the Windows version of FLEX
2) Download the Windows version of BISON
3) Download a C/C++ Compiler ( If you say TurboC , I’ll reach out through the monitor and thump your head ). I recommend DevCPP or Code::Blocks
4) Install all 3. It’s recommended to install in folders WITHOUT spaces in their names. I use ‘ C:\GNUWin32 ‘ for FLEX and BISON and ‘ C:\CodeBlocks ‘ for Code::Blocks
5) Now add the BIN folders of both folders into your PATH variable. Incase you don’t know how to go about this, see how to do it on Windows XP ,Windows Vista and Windows 7. You will have to add ‘ ;C:\GNUWin32\bin;C:\CodeBlocks\bin ‘ to the end of your PATH
6) Open up a CMD prompt and type in the following

C:\ flex —version
flex version 2.5.4

C:\> bison —version
bison (GNU Bison) 2.4.1
Written by Robert Corbett and Richard Stallman.

Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

C:\> gcc —version
gcc (GCC) 3.4.2 (mingw-special)
Copyright (C) 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

If you do not get the output as above, restart your system and try again.

That’s it! You now have a Bison and Flex set up! Now for some coding! 🙂

Create a Lex file, let’s say «exp.l» and open it up in your favorite text editor (read: Notepad++)

Similarly create a YACC file as well, say «exp.y» and edit it as follows

Now in the CMD prompt, navigate to the folder where the exp.l and exp.y files are and run the following commands:

C:\LT\example>flex exp.l

C:\LT\example>bison -dy exp.y

C:\LT\example>gcc lex.yy.c y.tab.c

At each step, assuming all is well, you won’t get any output. Note that the final step compiles the C files generated by FLEX and BISON. And generates a executable named a.exe (To use a different name, change last command to » gcc lex.yy.c y.tab.c -o nameofexecutable.exe » )

C:\LT\example>a.exe
666
EVEN NUMBER
C:\LT\example>a.exe
667
ODD NUMBER

Now just run the program ( through the command prompt itself ). For and even number input, it prints out «EVEN NUMBER» and exits and «ODD NUMBER» is printed for odd numbers. A simple example, but I guess it gets the point through!

PS The GnuWin project is a superawesome project which » provides ports of tools with a GNU or similar open source license, to Windows «. The number of packages that they’ve ported to Windows is amazing. Do check it out.

PPS Yes, I’m a FOSS/Linux enthusiast, but that doesn’t mean I have to praise Linux all day long! Projects like GNUWin, which take code to the masses, are nothing short of brilliant! Linux distributions have so many advantages over Windows for any real developer, but I honestly believe every developer has the right to » choose » his/her development OS and environment, be it PC, Linux or Mac. Do try out Linux distros as well (infact, I’d highly recommend you try a few before deciding which suits you best! Most distros are free!), but don’t get dragged down by an environment! An OS is simply a tool to enable you, the developer, to work your magic! 🙂

Читайте также:  Windows 10 не открываются свойства мой компьютер windows

Update : Here’s a Zip file of FLEX, BISON and the Source Code used in this post.

21 comments :

sir I am studying compiler design and i am be very much thanking for your help with lex and yacc

Nice article bro, I really like your technical articles, but why not just use Cygwin and then build the sources?

August 26, 2011 at 12:29 AM Anonymous said.

you can use windows flex and bison with minimal dependencies from http://sourceforge.net/projects/winflexbison/

Very nice piece of technical article. I like it very much mainly because:
1. it’s short, simple and addresses the issue stated in its title (thumbs up for that)
2. it’s exactly what I needed 😀

Anyway, I take the liberty to add the following: for those of you who are using GCC «4.5.0 20100311 (experimental)» (like me) you may want to add
%<
#include
#include
%>

to exp.y, right before %token EVEN ODD in order to have an error free compilation.

October 30, 2011 at 10:06 PM Anonymous said.

March 25, 2012 at 4:46 PM Anonymous said.

Great work.It is very useful for beginners of the compiler design.Thanx

i have installed the flex,bison,dev-cpp in windows xp. icopied the progrm from the example given and saved as lex.l and kkk.y. but while running in command prompt it shows the error of flex:can’t open lex.l and also same for bison.plz clarify me.

January 12, 2013 at 12:21 PM pradeep said.

How can you i use lex and yacc in visual c++ 2010?

January 19, 2013 at 4:50 AM Anonymous said.

when i try to compile using the command «gcc lex.yy.c y.tab.c» it shows the error» gcc is not recognized as an internal and external command «what can i do in order to inorder to compile

October 17, 2013 at 12:20 PM Anonymous said.

I love you man! thanks a lot for keeping it simple!

April 2, 2014 at 2:47 AM Anonymous said.

After writing the command
gcc lex.yy.c y.tab.c -o exp.exe

I am getting the following error.
exp.1:2:10: #include expects «FILENAME» or
exp.1:25:3: warning: no newine at end of file

Can anyone help me with this?

April 9, 2014 at 3:19 PM Anonymous said.

i am getting this error too!
error: #include expects «FILENAME» or

‘gcc’ is not recognized as an internal or external command,
operable program or batch file.

July 3, 2014 at 9:32 PM Anonymous said.

For those of you saying «‘gcc’ is not recognized as an internal or external command,
operable program or batch file.»
Please READ instructions! You need to download a compiler in Step 3, install it in Step 4, and add bin folders to your system path in Step 5.
If you need help with installing a compiler, try MinGW out. Or maybe try TDM-GCC instead.

October 11, 2014 at 7:38 AM Anonymous said.

bt what was the final command. i cant compile and run flex files.and rest of part i didn’t understand plz clarify it

March 23, 2015 at 4:40 PM Shashank said.

Thanks man this article saved me from a lot of trouble.

when i want to compile lex.yy.c following error is being generated. I have dev-cpp 5.11 TDM-GCC 4.9.2 with path variables set in windows 8. plz help how to fix this error
C:\prolex>gcc lex.yy.c
C:\Users\dsm\AppData\Local\Temp\ccyIiVSf.o:lex.yy.c:(.text+0x3c5): undefined reference to `yywrap’
C:\Users\dsm\AppData\Local\Temp\ccyIiVSf.o:lex.yy.c:(.text+0xc8b): undefined reference to `yywrap’
C:/Dev-Cpp/MinGW64/bin/../lib/gcc/x86_64-w64-mingw32/4.9.2/../../../../x86_64-w64-mingw32/lib/../lib
/libmingw32.a(lib64_libmingw32_a-crt0_c.o): In function `main’:
C:/crossdev/src/mingw-w64-v3-git/mingw-w64-crt/crt/crt0_c.c:18: undefined reference to `WinMain’
collect2.exe: error: ld returned 1 exit status

when i m writing in cmd to Compile the Flex program. flex exp.l the message appears «flex can’t open the ‘exp.l'»
same message for Bison, What to do.
PLZ Help.

gcc comand is not working

October 28, 2015 at 11:52 PM Anonymous said.

A very well written article. Keep up the good work,Sir!

December 10, 2015 at 12:55 AM SARITA said.

Оцените статью