Search code examples
c++attributesclangpragma

Attribute packed with C++ and clang


I thought that the double bracket notation was intended to replace __attribute__((foo)), but I'm not getting equivalence.

Clang toolchain set for C++14.

class [[packed]] test {};
class __attribute__((packed)) test2 {};

test has a warning about unknown attributed packed ignored. test2 has no warning. If I replace packed with a made-up attribute, both give warnings.

What's the best way to pack a struct in Clang?


Solution

  • I thought that the double bracket notation was intended to replace __attribute__((foo)), but I'm not getting equivalence.

    It's not meant to be entirely equivalent. The double bracket notation is for the C++ standard to introduce attributes with a more or less standard meaning. Those often exist already as compiler specific attributes, but it doesn't mean that all compiler specific attributes have a corresponding standard attribute. So you can't expect [[packed]] to be a thing just because __attribute__((packed)) is.

    Nevertheless, the standard does give compilers an option to add custom attributes that use double brackets. But such attributes are usually scoped. In this case, the custom attribute is named [[gnu::packed]]. As the name implies, it's vendor specific.