Error linking standard header file in gcc

I've a simple code - this works on other platforms but does not work in ubuntu.

#include <stdio.h>
#include <stdlib.h>
int main()
{
int x=99;
char str[100];
itoa(99, str, 10);
return 0;
}

Trying to compile in using terminal in gcc with :

gcc test.c

But I get the error:

/tmp/ccJN77g6.o: In function `main':
test.c:(.text+0x35): undefined reference to `itoa'
collect2: ld returned 1 exit status

Why so? prototype for itoa is included in stdlib.h

3

3 Answers

itoa doesn't seem to be ANSI C++ and thus is very likely to be not supported by gcc.

According to this source, a the following workaround is suggested:

This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
A standard-compliant alternative for some cases may be sprintf: sprintf(str,"%d",value) converts to decimal base. sprintf(str,"%x",value) converts to hexadecimal base. sprintf(str,"%o",value) converts to octal base.

A sprintf reference can be found here.

itoa function is not portable, non standard and most Linux compilers doesn't support it.

Instead you should use snprintf() function

Check the snprintf reference here

#include <stdio.h>
#include <stdlib.h>
int main()
{
int x=99;
char str[100];
// itoa(99, str, 10);
snprintf(str,10,"%d", x);
return 0;
}

I used the code you entered and I get the same error. It would appear that itoa() isn't ANSI C standard and doesn't work with GCC on Linux (at least the version I'm using). Things like this are frustrating especially if you want your code to work on different platforms (Windows/Linux/Solaris/whatever).

It is not a standard C function. Here are some links that might get you started to find a way around the function:

link1Stack overflow question

Hope it helps.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like