Search⌘ K
AI Features

Why do we need attributes?

Explore the purpose and benefits of attributes in C++ code, including how standard attributes since C++11 improve code expressiveness and cross-compiler compatibility. Learn why modern attributes replace compiler-specific annotations to help produce optimized and readable code.

Let’s start with an example

Have you ever used __declspec, __attribute or #pragma directives in your code?

Here is an example:

C++
// set an alignment
struct S { short f[3]; } __attribute__ ((aligned (8)));
// this function won't return
void fatal () __attribute__ ((noreturn));

Or for DLL import/export in MSVC:

C++
#if COMPILING_DLL
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT __declspec(dllimport)
#endif

Those are existing ...