混合野牛和C代码

时间:2015-01-14 12:06:36

标签: c compiler-construction bison yacc flex-lexer

这是我计划的一部分。

    %{
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    int yylex(void);
    int yylineno;
    char* yytext;
    void yyerror(const char *s) { printf("ERROR: %s\n", s); }
    void addID(char *ID);

%}

%union{ char * string;}


%%
    program: 
|DECLARE vdeclarations IN commands END
;

vdeclarations:
vdeclarations IDENTIFIER {addID($2);}
| IDENTIFIER {addID($1);}
;

最后的一些C函数

    struct list_ID {
    char *ID;
    int index;
    struct list_ID * next;
};
typedef struct list_ID list_ID;
list_ID * curr, * head;
head = NULL;
int i = 0;
void addID(char *s)
{
    curr = (list_ID *)malloc(sizeof(list_ID));
    curr->ID = strdup(s);
    curr->index = i++;
    free(s);
    curr->next = head;
    head = curr;
}

我只是想将所有IDENTIFIERS添加到链接列表中,但gcc会给我这样的错误。

kompilator.y:74:1: warning: data definition has no type or storage class [enable
d by default]
kompilator.y:74:1: error: conflicting types for 'head'
kompilator.y:73:19: note: previous declaration of 'head' was here
kompilator.y:74:8: warning: initialization makes integer from pointer without a
cast [enabled by default]
kompilator.y: In function 'addID':
kompilator.y:82:13: warning: assignment makes pointer from integer without a cas
t [enabled by default]
kompilator.y:83:7: warning: assignment makes integer from pointer without a cast
 [enabled by default]

所以不可能在野牛中制作这样的混合物吗?或者我的C代码部分有问题?

1 个答案:

答案 0 :(得分:2)

head = NULL; 

这是任何功能之外的声明。这是不允许的。

如果要初始化全局数据,请在声明时执行:

list_ID * curr, * head = NULL;

此外,您不应该投射malloc的结果。使用-Wall -Wextra.

进行编译时,请确保没有警告