9

I'm trying to convert an integer to a character to write to a file, using this line:

fputc(itoa(size, tempBuffer, 10), saveFile);

and I receive this warning and message:

warning: implicit declaration of 'itoa'

undefined reference to '_itoa'

I've already included stdlib.h, and am compiling with:

gcc -Wall -pedantic -ansi

Any help would be appreciated, thank you.

aytee17
  • 415
  • 2
  • 5
  • 9
  • 1
    I am guessing that itoa may not be present in the standard C library you are using. You could try specifying the flag `-fpermissive` to see if the code works. – GWW Mar 25 '11 at 04:46
  • 1
    There's no such function as `itoa` in the "official" standard library. Apparently the standard library you are using does not provide `itoa`. Your `-pedantic` and `-ansi` flags will not help anything. Quite the opposite, they can actually make things worse by hiding non-standard functions (I don't know whether they really do that). Try compiling without them. – AnT stands with Russia Mar 25 '11 at 04:49

2 Answers2

23

itoa is not part of the standard. I suspect either -ansi is preventing you from using it, or it's not available at all.

I would suggest using sprintf()

If you go with the c99 standard, you can use snprintf() which is of course safer.

char buffer[12];
int i = 20;
snprintf(buffer, 12,"%d",i);
chacham15
  • 13,719
  • 26
  • 104
  • 207
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • 1
    You need a bigger buffer to handle the negative sign. –  Feb 01 '14 at 03:22
  • 1
    @RocketRoy it was actually simply an example. The value `20` in the example fits just fine in a `char[10]` and that's the buffer size the OP was using. But yes, a signed 32 bit int would require `char[12]` to handle the sign and `\0` – Brian Roach Feb 01 '14 at 05:21
  • 1
    @BrianRoach while you are perfectly correct, for the sake of people who like to copy paste I have changed the size of the buffer in the example. – chacham15 Feb 01 '14 at 07:27
  • Brian's original answer illustrates the fact of the matter. Assuming that `int` would fit into a 12 byte string is completely incorrect, and if put out as fact, it could mislead people. For example, on AVR 8-bit systems, 'int's are often 16-bit (2- byte). – kevr Feb 10 '21 at 06:57
2

This here tells you that during the compilation phase itoa is unknown:

warning: implicit declaration of 'itoa'

so if this function is present on your system you are missing a header file that declares it. The compiler then supposes that it is a function that takes an unspecific number of arguments and returns an int.

This message from the loader phase

undefined reference to '_itoa'

explains that also the loader doesn't find such a function in any of the libraries he knows of.

So you should perhaps follow Brian's advice to replace itoa by a standard function.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177