Hmm. If you're willing to run another program before the compile,
you could run something like this from your compiler script or
makefile (although it need only be run once on any given target
machine):
/* Method of determining endian-ness is Jacob Navia's */
/* Adjust path and filename to suit your situation */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{ FILE *fp;
union
{ char c;
int i;
} u;
u.i = 0;
u.c = 1;
if (fp = fopen("/usr/include/endian.h","w"))
{ fprintf(fp,"#define %S_ENDIAN\n",(u.i&1)?"LITTLE":"BIG");
fclose(fp);
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
then in your application just
#include <endian.h>
#ifdef BIG_ENDIAN
/* Big endian code */
#else
/* Little endian code */
#endif
Of course, all of these union methods result in undefined behavior.
I think that the risk is lower if you make it an unsigned char and
assign a value to the integer and examine the unsigned char.
At any rate (from the C-FAQ):
10.16: How can I use a preprocessor #if expression to tell if a
machine is big-endian or little-endian?
A: You probably can't. (Preprocessor arithmetic uses only long
integers, and there is no concept of addressing.) Are you
sure you need to know the machine's endianness explicitly?
Usually it's better to write code which doesn't care.
See also question 20.9.
References: ISO Sec. 6.8.1; H&S Sec. 7.11.1 p. 225.
20.9: How can I determine whether a machine's byte order is
big-endian or little-endian?
A: One way is to use a pointer:
int x = 1;
if(*(char *)&x == 1)
printf("little-endian\n");
else printf("big-endian\n");
It's also possible to use a union.
See also questions 10.16 and 20.9b.
References: H&S Sec. 6.1.2 pp. 163-4.
It seems to be less of a problem to store an "X" in a union and
examine it as a "Y" with C99 than with previous iterations of the
standard, but in C89 I am pretty sure that the behavior is undefined
unless you are examining unsigned characters.
We have to compiler for dozens of platforms here. We just figure out
the endianness before hand and compile with an appropriate macro
definition.