13

如果我包括 stdlib.h 那么 itoa() 也无法识别。我的代码:

%{
#include "stdlib.h"
#include <stdio.h>
#include <math.h>
int yylex(void);
char p[10]="t",n1[10];
int n ='0';

%}
%union
{
char *dval;
}
%token ID
%left '+' '-'
%left '*' '/'
%nonassoc UMINUS
%type <dval> S
%type <dval> E
%%
S : ID '=' E {printf(" x = %sn",$$);}
;
E : ID {}
| E '+' E {n++;itoa(n,n1,10);printf(" %s = %s + %s ",p,$1,$3);strcpy($$,p);strcat($$,n1);}
| E '-' E {n++;itoa(n,n1,10);printf(" %s = %s – %s ",p,$1,$3);strcpy($$,p);strcat($$,n1);}
| E '*' E {n++;itoa(n,n1,10);printf(" %s = %s * %s ",p,$1,$3);strcpy($$,p);strcat($$,n1);}
| E '/' E {n++;itoa(n,n1,10);printf(" %s = %s / %s ",p,$1,$3);strcpy($$,p);strcat($$,n1);}
;
%%

main()
{
yyparse();
}

int yyerror (char *s)


{


}

运行代码后我得到:

gcc lex.yy.c y.tab.c -ll
12.y: In function ‘yyparse’:
12.y:24: warning: incompatible implicit declaration of built-in function ‘strcpy’
12.y:24: warning: incompatible implicit declaration of built-in function ‘strcat’
12.y:25: warning: incompatible implicit declaration of built-in function ‘strcpy’
12.y:25: warning: incompatible implicit declaration of built-in function ‘strcat’
12.y:26: warning: incompatible implicit declaration of built-in function ‘strcpy’
12.y:26: warning: incompatible implicit declaration of built-in function ‘strcat’
12.y:27: warning: incompatible implicit declaration of built-in function ‘strcpy’
12.y:27: warning: incompatible implicit declaration of built-in function ‘strcat’
/tmp/ccl0kjje.o: In function `yyparse':
y.tab.c:(.text+0x33d): undefined reference to `itoa'
y.tab.c:(.text+0x3bc): undefined reference to `itoa'
y.tab.c:(.text+0x43b): undefined reference to `itoa'
y.tab.c:(.text+0x4b7): undefined reference to `itoa'

我哪里错了?为什么找不到对 itoa 的引用?我也尝试过使用 <> 括号来表示 itoa。

4

2 回答 2

21

itoa是一些编译器支持的非标准函数。根据错误,您的编译器不支持它。你最好的选择是使用它snprintf()

于 2012-10-19T08:46:31.407 回答
6

sprintf以以下方式使用:

#include <stdio.h>

char *my_itoa(int num, char *str)
{
        if(str == NULL)
        {
                return NULL;
        }
        sprintf(str, "%d", num);
        return str;
}

int main()
{
        int num = 2016;
        char str[20];
        if(my_itoa(num, str) != NULL)
        {
                printf("%s\n", str);
        }
}

我希望这会节省别人的时间;)

于 2016-02-04T13:16:46.980 回答