在gcc上编译时发生错误

时间:2017-01-03 06:34:09

标签: c gcc

#include<stdio.h> 
#include<stdlib.h>
#include<string.h>
void main(void)
{
    int a,b,sub,i,count=0;char buffer[20],w[20];
    scanf("%d",&a);
    scanf("%d",&b);
    sub=a-b;
    if(sub>0)
    {
        scanf("%s",w); /*wrong answer*/
        itoa(sub,buffer,10);
        int l=strlen(buffer);
        for(i=0;i<l;i++)
        {
            if(w[i]==buffer[i])
                count++;
        }
        ((count==l || count==l-1) && w[0]!='0') ? printf("accepted") : printf("Not accepted");
    }
    else printf("Sub operation returned negative value");
}

编译器的输出是

prog.c:4:6: warning: return type of 'main' is not 'int' [-Wmain]
 void main(void)
      ^
prog.c: In function 'main':
prog.c:13:1: warning: implicit declaration of function 'itoa' [-Wimplicit-function-declaration]
 itoa(sub,buffer,10);
 ^
/home/HCDVgj/ccHBnrc7.o: In function `main':
prog.c:(.text.startup+0x61): undefined reference to `itoa'
collect2: error: ld returned 1 exit status

我没有使用任何长的int变量,但我仍然得到ld返回1存在。如何调试这些错误

2 个答案:

答案 0 :(得分:2)

  • int main()这是你应该做的第一件事。

  • scanf("%19s",w);这样更好。

  • itoa是非标准的(因此您无法在任何标准实施中找到它)更好地使用snprintf()

  • printf('%s",((count==l || count==l-1) && w[0]!='0') ? "accepted" : "Not accepted");我会说更紧凑。

使用snprintf

snprintf(target, size_of_target 1 , "%d", source 2 );

sprintf没有指定要写入的字节数的参数,这可能导致缓冲区溢出,这不是一件好事。

1:以字节为单位
2:source在这里是整数

为了清楚你的想法或更准确,很少有值得一提的事情

  • 您指定的输出不是c程序的输出...在编译过程中编译器遇到错误然后生成那些输出。 - 的 <子> CiaPan

  • main()不应为void返回类型,如果正常终止,则应返回0。异常终止通常由非零信号表示.- David C. Rankin

答案 1 :(得分:0)

我不知道你为什么要谈论&#34; long int变量&#34;。

可以通过将void main(void)更改为int main(void)并在结尾添加return 0;来修复第一个警告。

第二个警告告诉您编译器不知道itoa是什么。

以下链接器错误告诉您链接器(ld)也不知道itoa是什么,以及编译失败的原因。

itoa未知的原因是它不是标准功能,并且在您的平台上无法使用。