Using static on typedef struct - c

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

Related

How to use a linked list with a header file in C?

I have to create a program that performs various functions with a linked list. I must save the functions in a separate file from the main() but then I can't figure out how to include the list in the header file.
I tried different combinations and right now I have this in the linkedList.h file:
typedef struct list_elements* item;
And this in the linkedList.c
typedef struct list_elements{
int value;
struct list_elements *next;
}item
The problem is that when I try to compile the main.c I get the message: "request for member ‘value’ in something not a structure or union" and "request for member ‘next’ in something not a structure or union".
I looked on the suggested textbooks and online but I cannot find an explanation on how to use linked lists with header files?
(The functions work when I tested the whole thing in a single file, so I don't think they are the problem);
You are trying to typedef the same identifier twice as different types.
Remove the first typedef typedef struct list_elements* item; and put the second one in the header linkedList.h, which must be included in linkedList.c.
The declaration from your header defines type item as a pointer to a struct list_elements. The declaration from linkedList.c declares the same name, item, as an alias for type struct list_elements itself. Although this is not inherently wrong, it is certain to be confusing. It does make it wrong for linkedList.c to #include the header file, which ordinarily it would be appropriate for it to do.
You should make all your type declarations in the header file, and include it in both C source files to ensure that they share those declarations. Type declarations include at least typedefs, struct and union declarations, and function prototypes. This is not an exclusive list of things you might want to put in a header.
There is more than one way to do that:
one of them is to define the structures with the functions' prototype you want to use in a .h file, and the code of the functions in a separate .c (with the same prototypes written in the .h file of course), then you are now ready to use the structure in any other .c file by including your header file. e.g:
StType.h
typedef struct Something{
int a;
int b;
}
typedef struct anotherSomething{
int c;
int d;
}
int fct1();
int fct2();
Fct.c
include StType.h;
int fct1()
{
//...
}
void fct2()
{
//...
}
your program.c
include StType.h
int main()
{
Something s;
fct1();
}
I usualy does something like this.

Structs: what should go a header and what should go in the source?

If I have a source file mystruct.c and a corresponding header file, what is the proper way to define it in each file?
assume I have a structure:
typedef struct my_struct {
int a;
} MyStruct;
should it be placed like this in the header? or should it look more like this:
source file:
struct my_struct {
int a;
};
header file:
typedef struct my_struct MyStruct;
I have the same question about enums and unions.
Im basically looking for the standard way of defining these things so that they can be used in many other files without having to worry about redefinition errors.
Defining the contents of your struct in the .c file and just declaring the struct to exist in the header means that you need to provide a function to create the struct, e.g.
rc = my_struct_create(&s);
It has the advantage that you can change the contents of your struct without having to recompile dependent code - this is because the struct is opaque, the only way to create it is with your function and the only way to access any members of the struct will be through functions you define.
I'd personally recommend that approach for library code. Otherwise it really depends on what you're trying to achieve.
In the .h file, you would put the structure definition, and the function prototypes:
point.h
typedef struct {
int x, y;
} point;
point *initpt(int, int);
In the .c file, you would implement the functions:
point.c
point *initpt(int x, int y)
{
point *p;
p->x = x;
p->y = y;
return p;
}
It depends if the structure members are part of the public API or not. If the users of the API are not supposed to access the structure members, leave the structure definition to the .c file only. If they are supposed to know the implementation of the structure (for example because you want to allow them to access the members of the structure) put the structure definition in the .h. By principle be more restrictive first, and then if you have too, you can still change it later.

typedef struct in header file struct definition in c file

I have a typedef for a struct in sampleHeader.h that is similar to:
typedef struct example Example;
and I have in my sampleSource.c:
struct example{
char a[4];
char b[4];
char c[5];
}
Now for some reason when I return a pointer back to my main function which references a struct that has been created ( and malloc'd) and try to print out the values of each member I get an error along the lines of "cannot derefence incomplete type"
Any ideas?
In the header file you have only forward declared the struct. That's fine and you'll be able to declare pointers and references to the struct in the header (and any other header or cpp file that includes this header too).
As the compiler has only seen the definition in the cpp module, this is the only place that you'll be able to declare variables of type struct example by value or to dereference pointers to access members. Outside of the cpp file the compiler doesn't know how big the struct is or what is members are.
If you need to use the struct in multiple modules declare and define the struct together in the header.
Hard to say for sure without seeing the actual code, but....
struct example{
char a[4];
char b[4];
char c[5];
};
^ note the new semi colon.

extern vars and struct defined in other source file

Have two files with struct definitions. Header:
typedef struct _InputData InputData;
extern InputData input_data;
and source file:
struct _InputData{
char const*modification_l;
char const*amount_l;
char const*units_l;
};
InputData input_data = {...};
When i try to use input_data from other source file it gives me "invalid use of incomplete typedef ‘InputData’". I think i understand why it happened, but how i can deal with it in the gracefullest way.
You have do define the complete structure in the header file. Otherwise there is no way to know what fields it have, i.e. it's incomplete.
You can do this approach (more or less), but you need to define the struct as a pointer instead:
header
extern struct InputData* input_data;
source file:
struct InputData{
char const*modification_l;
char const*amount_l;
char const*units_l;
};
InputData* input_data;
...
input_data = malloc(sizeof(InputData));
You can use a pointer to a struct defined elsewhere, but not an instance. Compiler doesn't know what is the structure and how to calculate memory offsets for such a variable.
Why do you put the struct definition in the C file? put it in the header.

How to declare a structure in a header that is to be used by multiple files in c?

If I have a source.c file with a struct:
struct a {
int i;
struct b {
int j;
}
};
How can this struct be used in another file (i.e. func.c)?
Should I create a new header file, declare the struct there and include that header in func.c?
Or should I define the whole struct in a header file and include that in both source.c and func.c? How can the struct be declared extern in both files?
Should I typedef it? If so, how?
if this structure is to be used by some other file func.c how to do it?
When a type is used in a file (i.e. func.c file), it must be visible. The very worst way to do it is copy paste it in each source file needed it.
The right way is putting it in an header file, and include this header file whenever needed.
shall we open a new header file and declare the structure there and include that header in the func.c?
This is the solution I like more, because it makes the code highly modular. I would code your struct as:
#ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME
#define SOME_HEADER_GUARD_WITH_UNIQUE_NAME
struct a
{
int i;
struct b
{
int j;
}
};
#endif
I would put functions using this structure in the same header (the function that are "semantically" part of its "interface").
And usually, I could name the file after the structure name, and use that name again to choose the header guards defines.
If you need to declare a function using a pointer to the struct, you won't need the full struct definition. A simple forward declaration like:
struct a ;
Will be enough, and it decreases coupling.
or can we define the total structure in header file and include that in both source.c and func.c?
This is another way, easier somewhat, but less modular: Some code needing only your structure to work would still have to include all types.
In C++, this could lead to interesting complication, but this is out of topic (no C++ tag), so I won't elaborate.
then how to declare that structure as extern in both the files. ?
I fail to see the point, perhaps, but Greg Hewgill has a very good answer in his post How to declare a structure in a header that is to be used by multiple files in c?.
shall we typedef it then how?
If you are using C++, don't.
If you are using C, you should.
The reason being that C struct managing can be a pain: You have to declare the struct keyword everywhere it is used:
struct MyStruct ; /* Forward declaration */
struct MyStruct
{
/* etc. */
} ;
void doSomething(struct MyStruct * p) /* parameter */
{
struct MyStruct a ; /* variable */
/* etc */
}
While a typedef will enable you to write it without the struct keyword.
struct MyStructTag ; /* Forward declaration */
typedef struct MyStructTag
{
/* etc. */
} MyStruct ;
void doSomething(MyStruct * p) /* parameter */
{
MyStruct a ; /* variable */
/* etc */
}
It is important you still keep a name for the struct. Writing:
typedef struct
{
/* etc. */
} MyStruct ;
will just create an anonymous struct with a typedef-ed name, and you won't be able to forward-declare it. So keep to the following format:
typedef struct MyStructTag
{
/* etc. */
} MyStruct ;
Thus, you'll be able to use MyStruct everywhere you want to avoid adding the struct keyword, and still use MyStructTag when a typedef won't work (i.e. forward declaration)
Edit:
Corrected wrong assumption about C99 struct declaration, as rightfully remarked by Jonathan Leffler.
Edit 2018-06-01:
Craig Barnes reminds us in his comment that you don't need to keep separate names for the struct "tag" name and its "typedef" name, like I did above for the sake of clarity.
Indeed, the code above could well be written as:
typedef struct MyStruct
{
/* etc. */
} MyStruct ;
IIRC, this is actually what C++ does with its simpler struct declaration, behind the scenes, to keep it compatible with C:
// C++ explicit declaration by the user
struct MyStruct
{
/* etc. */
} ;
// C++ standard then implicitly adds the following line
typedef MyStruct MyStruct;
Back to C, I've seen both usages (separate names and same names), and none has drawbacks I know of, so using the same name makes reading simpler if you don't use C separate "namespaces" for structs and other symbols.
For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.
The extern declaration is not used for structure definitions, but is instead used for variable declarations (that is, some data value with a structure type that you have defined). If you want to use the same variable across more than one source file, declare it as extern in a header file like:
extern struct a myAValue;
Then, in one source file, define the actual variable:
struct a myAValue;
If you forget to do this or accidentally define it in two source files, the linker will let you know about this.
a.h:
#ifndef A_H
#define A_H
struct a {
int i;
struct b {
int j;
}
};
#endif
there you go, now you just need to include a.h to the files where you want to use this structure.

Resources