Sei Satzparad
Sei Satzparad

Reputation: 1177

Checking type sizes in C with macros

I'm writing a program that needs to have unsigned types with definite sizes. I need a uint8, uint16, uint32, and uint64, and I need them defined in types.h, in a way that they will always be defined correctly regardless of platform.

My question is, how can I check the sizes of different types on each platform using preprocessor macros, so that I can define my custom types correctly in the types.h header?

Upvotes: 1

Views: 2522

Answers (3)

Et7f3XIV
Et7f3XIV

Reputation: 629

   312 #define SDL_COMPILE_TIME_ASSERT(name, x)               \

   313        typedef int SDL_compile_time_assert_ ## name[(x) * 2 - 1]


   316 SDL_COMPILE_TIME_ASSERT(uint8, sizeof(Uint8) == 1);

   317 SDL_COMPILE_TIME_ASSERT(sint8, sizeof(Sint8) == 1);

   318 SDL_COMPILE_TIME_ASSERT(uint16, sizeof(Uint16) == 2);

   319 SDL_COMPILE_TIME_ASSERT(sint16, sizeof(Sint16) == 2);

   320 SDL_COMPILE_TIME_ASSERT(uint32, sizeof(Uint32) == 4);

   321 SDL_COMPILE_TIME_ASSERT(sint32, sizeof(Sint32) == 4);

   322 SDL_COMPILE_TIME_ASSERT(uint64, sizeof(Uint64) == 8);

   323 SDL_COMPILE_TIME_ASSERT(sint64, sizeof(Sint64) == 8);

Checkout SDL https://hg.libsdl.org/SDL/file/d470fa5477b7/include/SDL_stdinc.h#l316 they statically assert size at compile time. Like @Mehrdad say is can't be platform independant if your target doesn't have 64 bits integer.

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215221

C has standard typedefs for these. Do not define your own. They are called intN_t and uintN_t where N is 8, 16, 32, 64, etc. Include <stdint.h> to get them.

If you're using an ancient compiler that lacks stdint.h, you can simply provide your own with the appropriate typedefs for whatever broken platform you're working with. I would wager that on any non-embedded target you encounter without stdint.h:

  • CHAR_BIT is 8.
  • sizeof(char) is 1. <-- I'd wager even more on this one... ;-)
  • sizeof(short) is 2.
  • sizeof(int) is 4.
  • sizeof(long long), if the type exists, is 8.

So just use these as fill-ins for broken systems.

Upvotes: 4

user541686
user541686

Reputation: 210427

You can't even guarantee that all those types will exist on your platform (say, there might not even be a 64-bit integer), so you can't possibly write platform-independent code to detect them at compile-time.

Upvotes: 0

Related Questions