混合 Bison 和 C 代码

Mixing Bison and C code

这是我程序的一部分。

    %{
    #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();}
| IDENTIFIER {addID();}
;

最后还有一些 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]

难道不能在 bison 中进行这样的混合吗?还是我的 C 代码部分有问题?

head = NULL; 

这是任何函数之外的语句。这是不允许的。

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

list_ID * curr, * head = NULL;

此外,您不应该转换 malloc 的结果。确保在使用 -Wall -Wextra.

编译时出现零警告