Home > OS >  Is there a way to make a struct definition "private" to a single translation unit in C?
Is there a way to make a struct definition "private" to a single translation unit in C?

Time:10-23

In C, you can use the static keyword to make global variables and functions private to the file in which they're defined. The compiler won't export these symbols, and thus the linker will not allow other modules to use these definitions.

However, I'm struggling to figure out how to restrict a struct definition such that it doesn't get added as an exported symbol that could accidentally be used by another module during the linking process. I would like to restrict this to the only file in which its defined.

Here are my attempts thus far which I've been struggling with.

// structure that is visible to other modules
struct PrivateStruct
{
    int hello;
    int there;
};

// this seems to throw an error
static struct PrivateStruct
{
    int hello;
    int there;
};

// i would ideally like to also wrap in the struct in a typedef, but this definitely doesn't work.
typedef static struct PrivateStruct
{
    int hello;
    int there;
} PrivateStruct;

Edit: I realize if I just define this struct in the .c file, others won't know about it. But won't it still technically be an exported symbol by the compiler? It would be nice to prevent this behavior.

CodePudding user response:

I realize if I just define this struct in the .c file, others won't know about it. But won't it still technically be an exported symbol by the compiler?

No. Whether you are talking about structure tags or typedefed identifiers, these have no linkage. Always. There is no sense in which it would be reasonable to say that they are exported symbols.

This is among the reasons that header files are used in C. If you want to use a structure type in one compilation unit that is compatible with a structure type in a different compilation unit then compatible structure type declarations must appear in both. Putting the definition in a header makes it pretty easy to achieve that.

  • Related