tags:

views:

177

answers:

4

I've all this kind of functions.

ssize_t fuc1(int var1, void *buf, size_t count);
int func2(char *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 ?

+10  A: 

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.

Pavel Minaev
+1  A: 

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.

Billy ONeal
C++ TR1 includes `<stdint.h>` updated to the same level as C99 one.
Pavel Minaev
@Pavel Minaev: Thank you. Answer updated.
Billy ONeal
A: 

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

Péter Török
+1  A: 

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.

Thomas Matthews
This used to be a good solution. But once the <stdint.h> header was standardardized, the best practice was to use <stdint.h> if available, and if your compiler doesn't yet support it, at least define your own typedefs that are compatible with the names used in <stdint.h>. That way porting to a system that supports <stdint.h> in the future will be easy.
Stephen C. Steel