Using static on typedef struct

I use the following code a lot in C:

typedef struct { int member; } structname; 

Now i'm trying to keep that struct definition local to a particular source file, so that no other source file even knows the struct exists. I tried the following:

static typedef struct { int member; } structname; 

but GCC whines because of an illegal access specifier. Is it even possible to keep a struct's declaration private to a source file?

1

4 Answers

If you declare the typedef struct within a .c file, it will be private for that source file.

If you declare this typedef in a .h file, it will be accesible for all the .c files that include this header file.

Your statement:

static typedef struct 

Is clearly illegal since you are neither declaring a variable nor defining a new type.

2

All declarations are always local to a particular translation unit in C. That's why you need to include headers in all source files that intend to use a given declaration.

If you want to restrict the use of your struct, either declare it in the file in which you use it, or create a special header that only your file includes.

A structure definition is private to a source file unless placed in a shared header file. No other source file can access the members of the struct, even if given a pointer to the struct (since the layout is not known in the other compilation unit).

If the struct needs to be used elsewhere, it must be used only as a pointer. Put a forward declaration of the form struct structname; typedef struct structname structname; in the headerfile, and use structname * everywhere else in your codebase. Then, since the structure members appear only in one source file, the structure's contents are effectively 'private' to that file.

3

Hernan Velasquez's answer is the correct answer: there are several problems with your code snippet. Here's a counter-example:

/* This should go in a .h if you will use this typedef in multiple .c files */ typedef struct { int a; char b[8]; } mystructdef; int main (int argc, char *argv[]) { /* "static" is legal when you define the variable ... ... but *not* when you declare the typedef */ static mystructdef ms; 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like