[Linux] undefined reference to `itoa'

本文轉至http://blog.csdn.net/joeblackzqq/article/details/6934921

在linux寫了個簡單的C程序,裏面用到了itoa,但是編譯時提示“undefined reference to `itoa'”,本以爲加上-lc就行了,可結果還是一樣。上網發現,有人說這個函數在linux中是不存在的,一般用sprintf來代替。看下面代碼及註釋吧:

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. //#include <unistd.h>  
  4. #include <string.h>  
  5.   
  6. int num = 0;  
  7. char namebuf[100];  
  8. char prefix[] = "/tmp/tmp/p";  
  9.   
  10. char* gentemp()  
  11. {  
  12.     int length, pid;  
  13.   
  14.     pid = getpid();  
  15.     strcpy(namebuf, prefix);  
  16.     length = strlen(namebuf);  
  17.     //itoa(pid, &namebuf[length], 10);      // Unix版本:itoa()在頭文件<stdlib.h>中不存在  
  18.     sprintf(namebuf+length, "%d", pid);     // 使用sprintf將整數轉換成字符串  
  19.     strcat(namebuf, ".");  
  20.     length = strlen(namebuf);  
  21.     printf("before do...while\n");  
  22.     char command[1024] = {0};  
  23.     do   
  24.     {  
  25.         //itoa(num++, &namebuf[length], 10);  
  26.         sprintf(namebuf+length, "%d", num++);  
  27.         sprintf(command, "touch %s", namebuf);  // 通過touch來創建文件  
  28.         system(command);  
  29.         printf("command = %s, namebuf[%d]=%d\n", command, num-1, num-1);  
  30.     } while (num < 50 && access(namebuf, 0) != -1);  // access判斷文件是否存在  
  31.     printf("end of do...while\n");  
  32.   
  33.     return namebuf;  
  34. }  
  35.   
  36. int main( void )  
  37. {  
  38.     char *p = gentemp();  
  39.     printf("%s\n", p);  
  40.       
  41.     return 0;  
  42. }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章