Declaring a structure in a .h file and implementing in a .c file

this is my .h file:

struct _MyString; typedef struct _MyString MyString; 

I would like to declare its members in a .c file.

I tried:

 typedef struct MyString{ char * _str;// pointer to the matrix unsigned long _strLength; }MyString; 

but that will not work. how can i declare struct memebers in a .c file?

Thank you

+4
c
Nov 09 '10 at 17:59
source share
4 answers

You need only 1 typedef. Save the one you already have in the .h file and delete all the others.

Now the structure name is struct _MyString . This is what you should define in the .c file, not struct MyString : note the absence of "_".

So,

.h file

 struct _MyString; typedef struct _MyString MyString; 

.c file

 #include "file.h" struct _MyString { char * _str;// pointer to the matrix unsigned long _strLength; }; 
+9
Nov 09 '10 at 18:05
source share

What exactly does not work? If you try to access this structure from another .c file, this will not work. The declaration of the entire structure should be visible to all source files that use it - usually this is done by declaring it in the header file and #include in it in the source files.

Perhaps you confuse this with how functions are declared in the header file and defined in the source file — the declaration should be visible to all source files.

+2
Nov 09 '10 at 6:03
source share

If you need to use a structure in a .c file, then it needs a full definition of the structure at compilation. This is often done using #, including the header file with the definition.

If you do not need to use a structure definition, you can put it in a .c file, but it will only be available for functions inside this file.

It seems that you are trying to have an interface to your structure and only define it in the .c file to stop other parts of your code by accessing the structure. You can do this, but only with a pointer. For example:

 typedef struct MyString* MyString; 

And in the .c file you can define it. Instead, you can define functions with a Mypedring typedef.

0
Nov 09 2018-10-11T00:
source share

please clarify what does not work in order to get the right solution. I think the problem is that you need to include the .h file in the .c file, where you define the structure. Also include .h in every .c file that needs this struture. Make sure you break this structure in this case.

0
Nov 09 '10 at 18:14
source share



All Articles