【问题标题】:gcc error : undefined reference to `itoa'gcc 错误:未定义对“itoa”的引用
【发布时间】:2012-10-19 08:41:03
【问题描述】:

如果我包含 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。

【问题讨论】:

标签: gcc itoa


【解决方案1】:

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

【讨论】:

  • 请告诉我如何使用 snprintf() ?
  • 使用示例:snprintf (buff, sizeof(buf), "%d",n); // print int 'n' into the char[] buffer
  • 是的,我在 stackoverflow.com/questions/228005/… 看到了 itoa 的替代品
  • 当你有一个 char 指针并且它已经有一些值时它不起作用。它崩溃(分段错误:地址超出范围)。
【解决方案2】:

我通过以下方式使用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);
        }
}

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

【讨论】:

  • 如果我使用 char 指针并且它已经有一些值,我该怎么做?
  • @Shreyas 在 main 函数中显示,你可以调用 my_itoa() 用一个 int 值和一个缓冲区来存储结果字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-04
  • 1970-01-01
  • 2022-01-02
  • 2011-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多