留心int和pointer 因为integer与pointer大小相同,所以32位代码中常常把pointer转换为int或者unsigned int,以便算术运算。为了移植,你可以把pointer转换为unsigned long,因为long和pointer都是等长的,无论是在ILP32亦或LP64,但是,为了使代码更清晰,推荐用uintptr_t,uintptr_t和intptr_t都需要包含头文件inttypes.h。
例如:下面代码在64位环境下编译出错:
char *p;
p = (char *) ((int)p & PAGEOFFSET);
% cc ..
warning: conversion of pointer loses bits
改用uintptr_t后,无论是32位或者64位都没问题:
char *p;
p = (char *) ((uintptr_t)p & PAGEOFFSET);
留心int和long 在ILP32中,可能从未对int和long加以区分,因此,混用的情况非常多,看下面代码:
int waiting;
long w_io;
long w_swap;
...
waiting = w_io + w_swap;
% cc
warning: assignment of 64-bit integer to 32-bit integer
留心对齐 出于访问的效率,结构中通常会有所谓的hole,用来保证其中的所有数据成员,起始地址都是对齐模数的倍数。
例如:
struct bar {
int i;
long j;
int k;
char *p;
};
在ILP32中,sizeof(bar)应该是16字节;在LP64中,应该是32!因为此时long/char *的对齐模数都变为8,为了保证满足对齐要求,i/k都被扩展为8字节了。
又例如:
struct bar {
char *p;
long j;
int i;
int k;
}
此时,无需扩展,sizeof(bar)=8+8+4+4=24.
留心union union中的成员,必须保持平衡,也就是说,必须保证大小相等才有意义,所以移植时也要注意。
例如:
typedef union {
double _d;
long _l[2];
} llx_
在ILP32中,两者大小相同,都是8字节;移植到LP64,前者不变,后者为16字节,此时union已无意义,应改为:
typedef union {
double _d;
int _l[2];
} llx_
留心常量类型 在常量表达式中,精度的缺失会导致数据截断,例如:
int i = 32;
long j = 1 << i;
warning: left shift count >= width of type
什么意思?编译器抱怨左移的位数超过了数据类型的长度,结果就是j为0。
留心derived data types 例如,这些定义在sys/types.h中的数据类型,其大小会随ILP32或者LP64而变化:
* clock_t, which represents the system time in clock ticks
* dev_t, which is used for device numbers
* off_t, which is used for file sizes and offsets
* ptrdiff_t, which is the signed integral type for the result of subtracting two pointers
* size_t, which reflects the size, in bytes, of objects in memory
* ssize_t, which is used by functions that return a count of bytes or an error indication
* time_t, which counts time in seconds