开发者

How to maintain fixed size of C variable types over different machines?

I've all this kind of functions.

ssize_t fuc1(int var1, void *buf, size_t count);
int func2(char开发者_JAVA技巧 *charPtr, int mode, int dev);
short func3( long var2);

problem is that data types in C has different sizes when compiled on different machines(64bit & 32bit). This is true for even void*. For some reasons. I need to ensure that these sizes all are same on every machine(64bit & 32bit). So, how should I modify these ?


Use C99, <stdint.h>, and int32_t etc types. More details on Wikipedia.

There's no way to do this for pointer types, because they are, by definition, platform-specific. There is no valid use case in which you could possibly need them to be consistent, because they are not serializable. If you use a pointer variable to store pointer and other data (e.g. depending on some flag), use a union of some exact integral type with a pointer type. Alternatively, use C99 uintptr_t, and cast to pointer when you need to treat it as such.


The old fashioned method to solve your dilemma is to use macros to define a generic type and have these macros defined based on the target platform:

datatypes.h

#ifndef DATATYPES_H
#define DATATYPES_H

#ifdef PLATFORM_32_BIT
typedef UINT32 unsigned int; // unsigned 32-bit integer
typedef UINT16 unsigned short;
typedef UINT08 unsigned char;
#else
// Assume 64 bit platform
typedef UINT32 unsigned short;
#endif

#endif // DATATYPES_H

When you absolutely need a 32-bit unsigned variable, you will use the UINT32 type. The platform definition can be passed to the compiler on the command line.

Since I have not worked on a 64-bit platform, you will have to research the bit sizes of the POD types.


You can't, at least not within C++03 or C89. C99 has the <stdint.h> header you can use, which defines types like uint32_t, etc, but you're outta luck for C++.

If you need it to work in C++03 you need to use something like Boost::Integer EDIT or have an implementation of TR1 available.


The POSH library (Portable Open Source Harness) may be of help to you. This is created by Brian Hook, author of Write Portable Code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜