Question:
How do you write a compiler in C?
?
2010-01-09 01:47:14 UTC
Please give me the steps on how to build a compiler. I know about lex & yacc (flex & bison too) for building the parser, what else do I need to do?
Three answers:
jplatt39
2010-01-09 03:45:07 UTC
Writing an interpreter is a common assignment for CS students. I ended up writing an adventure game (text-based) in C but an adventure game is a type of interpreter: you enter the commands, it parses and interprets them and acts based on that. All of which means you don't need lex, yacc, flex or even scheme to write your parser. You can write it in C though there may be advantages to using these other languages. That's the good news.



There are really two types of compilers: One, such as Java or older Pascal compilers, compiles the language into some artificial byte code where tokens often only a few bytes long are interpreted and executed by a program. In the other, the program is translated into assembly language, the assembly language is compiled into a machine language object file, and the object file is linked with libraries to create an executable.



That's where things get a little hairy. To do an executable file for your OS you have to understand what the format for your file is and you have to create routines which will run and load your programs and to do housecleaning such as freeing arrays when you finish. I will assume, since you list so many GNU tools, you have access to gcc and gdb and can call them from the command line (whether you are aware of it or not. They are called by IDEs like Dev-C++). Compile a simple program with the command gcc -g and run the executable with gdb and the program name -- again, from the command line. Do a listing, set a break point (near the end is better for this) run to the breakpoint then step until it terminates. You WILL get to see the housecleaning the GCC libraries do. For a compiler that is your responsibility.



You might be able to just write the front end -- translate your code into assembler then feed it to as or yasm which will give you access to other libraries through the relevant linkers, but writing a compiler into an executable file is HARD stuff. Are you sure you wouldn't rather just do an interpreter?
MichaelInScarborough
2010-01-09 03:06:15 UTC
Here is a list of compilers, which are free and partly come with "C" source code.

http://www.bloodshed.net/compilers/index.html#free_comps

Is it this, what you are looking for?
oops
2010-01-09 02:00:28 UTC
Learn assembly, so you can translate source code into assembly. Then translate that assembly into machine code.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...