'best way to access struct variable from header files that defined in c file

I declared a struct in main.c file and i have functions in func1.c func2.c func1.h func2.h files.

main.c:

#include <stdio.h>
#include "func1.h"
#include "func2.h"

    struct mystruct{
    someting
    };

main(){
 struct mystruct var ={...};
 myfunc(var);
}

func1.h:

void myfunc(struct mystruct);

And definition is in func1.c. Similar for func2 files. I got compilation errors, it is obvious that problem is header file dont have declaration of mystruct and so cant use it. So what is the way to overcome that problem? Adding a new header file for struct or using extern keyword what i read. What is approprite choice i couldnt figure out at that point.

c


Solution 1:[1]

struct mystruct{
//something
};

Should be defined in a header file which all your c files that need it has access to.

mytypes.h

#ifndef mytypes_h
#define mytypes_h

struct mystruct{
 int something;
};

#endif

func1.h

#ifndef func1_h
#define func1_h

#include "mytypes.h"
void myfunc(struct mystruct);

#endif

func1.c

#include "func1.h"
void myfunc(struct mystruct){
 //do soemthing with struct
}

Then your main can include func1.h which already mytypes.h

main.c

#include "func1.h"

int main(){
 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1