Reputation: 385
this is my .h file:
struct _MyString;
typedef struct _MyString MyString;
i would like to declare its members in the .c file.
i tried:
typedef struct MyString{
char * _str;// pointer to the matrix
unsigned long _strLength;
}MyString;
but it doesn't work. how do i declare the struct's memebers in the .c file?
thank you
Upvotes: 4
Views: 18554
Reputation: 1868
please be clear on what is not working to get a correct solution. what is my guess could be the problem is that you need to include .h file in the .c file where you define the structure. Also incldue .h in every .c files that needs this struture. Make sure you extern this structure in that case.
Upvotes: 0
Reputation: 8917
If you need to use a struct in a .c file then it needs the full definition of the struct when being compiled. This is often done by #including a header file with the definition.
If you don't need to share the struct definition, you can place it inside a .c file but it will only be visible to functions within that file.
It seems that you're trying to have an interface to your structure and only define it in a .c file to stop other parts of your code accessing the structure. You can do that but only via a pointer. So for example:
typedef struct MyString* MyString;
And in the .c file you can define it. You can define functions using the MyString typedef instead.
Upvotes: 0
Reputation: 108978
You need only 1 typedef. Keep the one you already have in the .h file and delete all others.
Now, the struct name is struct _MyString
. That is what you should define in the .c file, not struct MyString
: notice the absence of the '_'.
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;
};
Upvotes: 13
Reputation: 70721
What exactly isn't working? If you're trying to access this structure from another .c
file, that won't work. The entire structure declaration must be visible to all source files that use it - typically this is done by declaring it in a header file and #include
-ing it in the source files.
Maybe you're confusing this with how functions are declared in a header file and defined in a source file - the declaration must still be visible to all source files.
Upvotes: 2