Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static on typedef struct

Tags:

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?

like image 263
nuju Avatar asked Sep 16 '12 05:09

nuju


People also ask

Can typedef be static?

typedef cannot be used along with static as both typedef and static are storage classes. If you define a variable as typedef static int a; then there exist multiple storage classes for the variable a . Storage classes are used to define the scope (visibility) and life-time of variables and/or functions.

Can you make a struct static?

A structure declaration cannot be declared static, but its instancies can. You cannot have static members inside a structure because the members of a structure inherist the storage class of the containing struct. So if a structure is declared to be static all members are static even included substructures.

Should you use typedef struct in C?

Using typedef struct results in a cleaner, more readable code, and saves the programmer keystrokes​. However, it also leads to a more cluttered global namespace which can be problematic for large programs.

Can typedef and struct have same name?

You can't "typedef a struct", that doesn't mean anything.


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

like image 155
Hernan Velasquez Avatar answered Sep 30 '22 16:09

Hernan Velasquez