C implementations differ substantially. ANSI C reduces but does not eliminate the incompatibilities; meanwhile, many users wish to compile GNU software with pre-ANSI compilers. This chapter gives recommendations for how to use the more or less standard C library functions to avoid unnecessary loss of portability.
sprintf. It returns the number of characters written on some systems, but not on all systems.
mainshould be declared to return type
int. It should terminate either by calling
exitor by returning the integer status code; make sure it cannot ever return an undefined value.
realloc. Most GNU programs use those functions just once, in functions conventionally named
xrealloc. These functions call
realloc, respectively, and check the results. Because
xreallocare defined in your program, you can declare them in other files without any risk of type conflict. On most systems,
intis the same length as a pointer; thus, the calls to
reallocwork fine. For the few exceptional systems (mostly 64-bit machines), you can use conditionalized declarations of
realloc---or put these declarations in configuration files specific to those systems.
strcpy strncpy strcat strncat strlen strcmp strncmp strchr strrchrThe copy and concatenate functions work fine without a declaration as long as you don't use their values. Using their values without a declaration fails on systems where the width of a pointer differs from the width of
int, and perhaps in other cases. It is trivial to avoid using their values, so do that. The compare functions and
strlenwork fine without a declaration on most systems, possibly all the ones that GNU software runs on. You may find it necessary to declare them conditionally on a few systems. The search functions must be declared to return
char *. Luckily, there is no variation in the data type they return. But there is variation in their names. Some systems give these functions the names
rindex; other systems use the names
strrchr. Some systems support both pairs of names, but neither pair works on all systems. You should pick a single pair of names and use it throughout your program. (Nowadays, it is better to choose
strrchrfor new programs, since those are the standard ANSI names.) Declare both of those names as functions returning
char *. On systems which don't support those names, define them as macros in terms of the other pair. For example, here is what to put at the beginning of your file (or in a header) if you want to use the names
#ifndef HAVE_STRCHR #define strchr index #endif #ifndef HAVE_STRRCHR #define strrchr rindex #endif char *strchr (); char *strrchr ();
Here we assume that
macros defined in systems where the corresponding functions exist.
One way to get them properly defined is to use Autoconf.
Go to the first, previous, next, last section, table of contents.