Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

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 ?

like image 373
Alex Avatar asked Dec 05 '22 03:12

Alex


2 Answers

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.

like image 97
Pavel Minaev Avatar answered May 07 '23 10:05

Pavel Minaev


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.

like image 40
Thomas Matthews Avatar answered May 07 '23 11:05

Thomas Matthews