1

Consider this class:

class C3
{
public:
    uint16_t p1;
    uint16_t p2;
    uint8_t p3;
};

sizeof(C3) is 6. Is there any compiler routine to bypass alignment and force it's size to be 5? I tried to use alignas without success...

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
jpo38
  • 20,821
  • 10
  • 70
  • 151
  • this should be answered by https://stackoverflow.com/questions/21092415/force-c-structure-to-pack-tightly – Mircea Ispas Jun 30 '20 at 11:04
  • 1
    Does this answer your question? [Force C++ structure to pack tightly](https://stackoverflow.com/questions/21092415/force-c-structure-to-pack-tightly) – Mircea Ispas Jun 30 '20 at 11:05
  • 2
    Your title is misleading. Your structures *are* aligned. Each member is aligned by the compiler and padding needed to ensure that alignment is inserted automatically. From your question it's clear though that what you want is *not* alignment but a *packed* structure without padding. – Jesper Juhl Jun 30 '20 at 11:17

2 Answers2

2

With the MSVC compiler (you have included the VS-2015 tag), you can use the #pragma pack directive to set padding options for classes and structures. This also allows you to save/restore 'default' settings, using the push and pop options.

The following short example demonstrates this:

#include <iostream>

class C3 {
public:
    uint16_t p1;
    uint16_t p2;
    uint8_t p3;
};

#pragma pack(push, 1) // Save current packing and set to single-byte
class C4 {
public:
    uint16_t p1;
    uint16_t p2;
    uint8_t p3;
};
#pragma pack(pop) // Restore saved packing

class C5 {
public:
    uint16_t p1;
    uint16_t p2;
    uint8_t p3;
};

int main()
{
    std::cout << sizeof(C3) << std::endl; // 6
    std::cout << sizeof(C4) << std::endl; // 5
    std::cout << sizeof(C5) << std::endl; // 6 (again)
    return 0;
}

Many other compilers support directives equivalent to the MSVC #pragma pack.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
1

Similar to answer by Adrian, you could also do for some compiler that might not support #pragma pack:

class  C3
{
public:
    uint16_t p1 __attribute__((packed));
    uint16_t p2 __attribute__((packed));
    uint8_t p3;
};
Ranoiaetep
  • 5,872
  • 1
  • 14
  • 39