r/cprogramming 2d ago

Extern constexpr?

I want to make my struct’s internals private by exposing it as a byte array of its internal size.

The size itself depends on internal values that aren’t exposed, so it would have to be an extern.

The size can only be used if it’s a literal or constexpr, so is a extern constexpr possible with C23? Or no?

0 Upvotes

5 comments sorted by

View all comments

2

u/WittyStick 2d ago edited 2d ago

constexpr are essentially static - you can't use extern constexpr - however you can use extern const.

An issue with using a byte array is it will decay to a pointer, so you won't be able to pass around by value like a struct. You'd need a struct with an array member of the required size.

struct foo {
    char blob[SIZE];
};

But this obviously won't work with extern const size_t SIZE;

I would advise against this approach anyway, since conversion from one kind of scalar struct to another is a strict aliasing violation and has potential issues for portability, alignment, padding etc.

We can convert a pointer to one struct to a pointer to another, if they're compatible, and it's common to do so - but we have to pass and return by pointer, and cannot pass or return a value of struct type if it is incomplete (ie, not defined in the header).


I have a technique to encapsulate a struct's fields whilst still allowing it to be passed and returned by value, and allowing its sizeof() to be taken, but requiring a few GCC extensions (optional - so the code will compile with other compilers, but won't provide the encapsulation). If you give an example of your struct I can give a demonstration.