I'd like to know when the size of a struct does not equal the combined size of it's members, in other words, when it is padded. gcc has a warning option to do exactly that, -Wpadded
.
From https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html : "Warn if padding is included in a structure, either to align an element of the structure or to align the whole structure."
Using this option didn't seem to catch padding where it should've though, so I wrote a simple test to demonstrate my issue:
#include <iostream>
#include <cstdint>
using namespace std;
struct test {
uint16_t a;
uint8_t b;
} test;
int main() {
cout << sizeof(test) << ", " << alignof(test) << std::endl;
return 0;
}
compiling this with g++ test.cpp -Wpadded
outputs warning: padding struct size to alignment boundary
, and running the executable gives 4, 2
, exactly as I'd expect. Changing the struct to
struct test {
uint8_t b;
uint16_t a;
} test;
and running the resulting executable gives 4, 2
, but no warning is given.
Both structs have the same size and alignment, the size of uint8_t
is obviously 1 byte, and uint16_t
2, so shouldn't I be getting a warning here? A page talking about various gcc options ( https://interrupt.memfault.com/blog/best-and-worst-gcc-clang-compiler-flags ) has a test similar to this one, and according to them, a warning is output in both situations.
I also ported the code to C (without the prints)
#include <stdint.h>
struct test {
uint8_t b;
uint16_t a;
} test;
int main() {
return 0;
}
And got the same result.
I'm using gcc 8.1.0 from MinGW-W64.
1条答案
按热度按时间af7jpaap1#
答案在评论中,但对于那些只会在“大帖子”中寻求答案的人来说:
正如@ssbssa所建议的:
请尝试使用-mno-ms-bitfields。
在
-Wpadded
和-mno-ms-bitfields
标志都处于活动状态的情况下进行编译时,它将起作用。