简体   繁体   中英

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?

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.

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; 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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM