⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.c

📁 一个C语言的编译器
💻 C
字号:
#include "globals.h"
#include "util.h"
#include "scan.h"
#include "parse.h"
#include "symtab.h"
#include "analyze.h"
#include "CodeGen.h"

#define NO_ANALYZE FALSE
void print_process();
/* allocate global variables */
int lineno = 0;
FILE * source;
FILE * listing;
FILE * inter_code;

/* allocate and set tracing flags */
int TraceScan = TRUE;
int TraceParse = TRUE;
int TraceAnalyze = TRUE;

int Error = FALSE;

int main(int argc, char * argv[])
{
	TreeNode * syntaxTree;
	char cfile[20], codefile[20];	/* sourse code file name */
	strcpy(codefile, "tmp.c");
	if (strchr(codefile, '.') != NULL) {
		int len = strcspn(codefile, ".");
		strncpy(cfile, codefile, len);
		cfile[len] = '\0';
	}
	else {
		strcpy(cfile, codefile);
		strcat(codefile, ".c");
	}
	source = fopen(codefile,"r");
	if (source==NULL)
	{ 
		printf("File %s not found!\n", codefile);
		exit(1);
	}
	strcpy(codefile, cfile);
	strcat(codefile, ".txt"); 
	listing = fopen(codefile,"w"); 
	if (listing == NULL)
	{ 
		printf("Unable to open %s\n", codefile);
		exit(1);
	}

	/* compilation begins here */
	syntaxTree = parse();
	if (TraceParse) {
		fprintf(listing,"\nSyntax tree:\n");
		printTree(syntaxTree);
	}
#if !NO_ANALYZE
	if (!Error)
	{
		fprintf(listing,"\nBuilding Symbol Table...\n");
		buildSymtab(syntaxTree);
		fprintf(listing,"\nChecking Types...\n");
		typeCheck(syntaxTree);
		fprintf(listing,"\nType Checking Finished\n");
	}
#if !NO_CODE
	if (!Error)
	{ 
		strcpy(codefile, cfile);
		strcat(codefile, ".asm"); 
		inter_code = fopen(codefile,"w");
		if (inter_code == NULL)
		{ 
			printf("Unable to open %s\n", codefile);
			exit(1);
		}
		pTable = GlobalTable;
		print_process();
		StackSegment();       //堆栈段定义
		DataSegmentBegin();   //数据段定义
		DataSegment(syntaxTree);
		DataSegmentEnd();
		CodeSegmentBegin();   //代码段定义
		write();
		write_sub();
		CodeGen_TreeNode(syntaxTree);
		CodeSegmentEnd();
		fclose(inter_code);
	}
#endif
#endif

	fclose(source);
	fclose(listing);
	return 0;
}

void print_process()  //打印tmp.c
{
    char ch;
    int i=0;
    int j=0,hang;
    char string[100][100];
    FILE *f;
    f=fopen("tmp.c","r");
    ch=fgetc(f);
    string[j][i]=ch;
    while(ch!=EOF)
    {   if(ch=='\n')
            {   string[j++][i]='\0';
                i=0;
             }
        putchar(ch);    
        string[j][i++]=ch;
        ch=fgetc(f);
        hang=j;         
    }
	printf("\n");
    fclose(f);
} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -