简体   繁体   中英

clang compaining about __attribute__((packed)) even though the struct needs to be packed

I have a struct, which needs to be packed (without packing the size is 20 bytes, but I need 16 to be able to read/write it). When I added the packed attribute I got error: packed attribute is unnecessary for warnings for all the members of the struct. When silencing the error with the pragmas, the code compiles fine and the size of the struct is 16, but if I remove the pragmas it fails (since I'm using -Werror ). Is clang just issuing this warning incorrectly or am I doing something wrong?

#include <cstdint>

typedef struct __attribute__((packed))
{
    uint16_t wFormatTag;
    uint16_t nChannels;
    uint32_t nSamplesPerSec;
    uint32_t nAvgBytesPerSec;
    uint16_t nBlockAlign;
}
WAVEFORMAT;

int main()
{
    WAVEFORMAT w;
    (void)w;
}

I am using the Xcode9 toolchain:

clang -v
Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin16.7.0

Which generates the warning when compiled with -Weverything :

clang++ -Weverything pack.cpp

pack.cpp:8:10: warning: packed attribute is unnecessary for 'wFormatTag' [-Wpacked]
    WORD wFormatTag;
        ^
...

Indeed it appears that clang issued that warning on your code incorrectly. This has been fixed in recent clang versions.

In particular, the warning does not reproduce with the clang 6.0 release candidate ( clang version 6.0.0-svn323772-1~exp1 ). I was able to replicate the warning with previous clang versions, including 5.0.1, 4.0.0, and 3.8.0.

I believe this is the clang commit in which the issue was fixed:
https://reviews.llvm.org/D34114

Unfortunately, it will probably take some time until Xcode's clang sees this fix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM