我正在 lex 和 yacc 中实现一个 sql 解析器, 因为我使用了一个符号表,我将其保存在单独的 .h 文件(sql.h)中,并且在这个头文件中我有一些函数声明。 这些函数的定义保存在 .c 文件 (sql.c) 中。现在我已将 sql.h 包含在 sql.c 中, 我在 lex 文件(1.l)和 yacc 文件(1.y)中引用了 sql.h 中的符号和函数。
问题是我无法为此编写正确的 makefile。 我收到诸如多个声明之类的错误。 我在哪里包含哪个文件以及如何编写依赖项? 请帮忙。我已经寻找了解决方案,但我没有得到它......
更新:
我这样编译代码:
lex 1.l yacc -d 1.y gcc lex.yy.c y.tab.c sql.c -ll -ly
I get the following errors after the third command of gcc:
In file included from 1.l:5: sql.h:17: warning: ‘SQL’ initialized and declared ‘extern’ sql.h:18: warning: ‘SQL_SEL’ initialized and declared ‘extern’ 1.l: In function ‘makeTable’: 1.l:80: warning: assignment from incompatible pointer type In file included from 1.y:7: sql.h:17: warning: ‘SQL’ initialized and declared ‘extern’ sql.h:18: warning: ‘SQL_SEL’ initialized and declared ‘extern’ sql.c:3: error: redefinition of ‘SQL’ sql.h:15: note: previous definition of ‘SQL’ was here sql.c:4: error: redefinition of ‘SQL_SEL’ sql.h:16: note: previous definition of ‘SQL_SEL’ was here
sql.h:
#ifndef SQL_H
#define SQL_H
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
struct sym_table {
char *token;
char *value;
struct sym_table *next;
};
struct sym_select {
char **cols;
};
extern struct sym_table *SQL = NULL;
extern struct sym_select *SQL_SEL = NULL;
void addSymbol(char *, char *);
void print(struct sym_table *);
void showTable(struct sym_table *);
void makeTable(struct sym_table *, int);
sql.c:
#include "sql.h"
struct sym_table *SQL = NULL;
struct sym_select *SQL_SEL = NULL;
以及sql.h中声明的函数的定义
1.l文件:
%{
#include <stdio.h>
#include <stdlib.h>
#include "y.tab.h"
#include "sql.h"
int lineno=1;
void makeTable(struct sym_table *, int);
%}
.....以及其他 lex 文件
1.y
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern int lineno;
extern void yyerror(char *);
#include "sql.h"
%}
...以及其他 yacc 文件数据
<小时/>你能建议我一些其他方法来解决这个问题吗?
最佳答案
请发布您的 Makefile。据我了解,代码也有问题,而不仅仅是 Makefile。或者您可能尝试从 1.l
生成 1.o
并从 1.y< 生成不同的
.1.o
/
通常依赖关系应该类似于:
1l.o: 1.l sql.h; # lex invocation
1y.o: 1.y sql.h; # bison invocation
sql.o: sql.c sql.h; # cc invocation
prog: 1l.o 1y.o sql.o; # ld invocation
您可能还需要依赖 token 的声明文件。
编辑: 啊,所以您可能需要将该表的定义放入一个文件中,并将声明放入 header 中。您必须首先了解C中声明和定义的区别。例如,如果您有以下文件:
aaa.h
int arr[]={1};
aaa.c
#include“aaa.h”
bbb.c
#include“aaa.h”
然后您尝试cc -o aaa aaa.c bbb.c
,您会收到多重定义错误。这意味着,实际的数组必须位于一个文件中,并且在 header 中它应该类似于 extern int arr[];
更新:
您应该在 sql.h 中删除对 NULL 的设置。这只是一个声明,某处有这样那样的变量。实际值要在sql.c中赋值。
关于c - sql 解析器的 Makefile...编写依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5133325/