Next: , Previous: , Up: Writing C   [Contents][Index]


5.6 Portability between CPUs

Even GNU systems will differ because of differences among CPU types—for example, difference in byte ordering and alignment requirements. It is absolutely essential to handle these differences. However, don’t make any effort to cater to the possibility that an int will be less than 32 bits. We don’t support 16-bit machines in GNU.

You need not cater to the possibility that long will be smaller than pointers and size_t. We know of one such platform: 64-bit programs on Microsoft Windows. If you care about making your package run on Windows using Mingw64, you would need to deal with 8-byte pointers and 4-byte long, which would break this code:

printf ("size = %lu\n", (unsigned long) sizeof array);
printf ("diff = %ld\n", (long) (pointer2 - pointer1));

Whether to support Mingw64, and Windows in general, in your package is your choice. The GNU Project doesn’t say you have any responsibility to do so. Our goal is to replace proprietary systems, including Windows, not to enhance them. If people pressure you to make your program run on Windows, and you are not interested, you can respond with, “Switch to GNU/Linux — your freedom depends on it.”

Predefined file-size types like off_t are an exception: they are longer than long on many platforms, so code like the above won’t work with them. One way to print an off_t value portably is to print its digits yourself, one by one.

Don’t assume that the address of an int object is also the address of its least-significant byte. This is false on big-endian machines. Thus, don’t make the following mistake:

int c;
…
while ((c = getchar ()) != EOF)
  write (file_descriptor, &c, 1);

Instead, use unsigned char as follows. (The unsigned is for portability to unusual systems where char is signed and where there is integer overflow checking.)

int c;
while ((c = getchar ()) != EOF)
  {
    unsigned char u = c;
    write (file_descriptor, &u, 1);
  }

Avoid casting pointers to integers if you can. Such casts greatly reduce portability, and in most programs they are easy to avoid. In the cases where casting pointers to integers is essential—such as, a Lisp interpreter which stores type information as well as an address in one word—you’ll have to make explicit provisions to handle different word sizes. You will also need to make provision for systems in which the normal range of addresses you can get from malloc starts far away from zero.


Next: , Previous: , Up: Writing C   [Contents][Index]