How to extern structure in c language. So that I can use a structure into b.
+4
A:
I'm assuming b is another source file. You can so something like:
file: file.h
#ifndef _FILE_H_
#define _FILE_H_
struct emp {
char name[100];
};
#endif
file: a.c
#include "file.h"
extern struct emp e; // declare struct var as extern.
int main() {
printf("Name = %s\n",e.name);
return 0;
}
file: b.c
#include "file.h"
struct emp e = {"stackoverflow"}; // struct var defined here.
On running:
$ gcc *.c && ./a.out
Name = stackoverflow
You question is very unclear and you are not new on SO.
codaddict
2010-02-04 06:38:15
First thanks a lot for your answer. And I accept I am not be able to clearly describe my question due to my poor English.I have try your code but when I include file.h into two separate files compiler give me the error of multiple deceleration of structure emp.
Arman
2010-02-04 06:44:09
You will need something like #ifndef FILE_H #define FILE_H [contents of file.h] #endifAround file.h
Richo
2010-02-04 06:48:07
Have my last upvote for today, but you should take Richo's suggestion. @Richo, the term for that is an "include guard."
Chris Lutz
2010-02-04 06:56:31
@Richo,Chris: Thanks.
codaddict
2010-02-04 07:00:58
Thanks Richo for your comment.
Arman
2010-02-04 07:07:52
No probs all, I learned something new as well :)
Richo
2010-02-04 13:27:03
A:
Extern struct works as well as extern, at least when the extern is in the header file and the actual struct is in a cpp file that includes that header. I don't think "extern struct" is necessary so much as just "extern".
Anonymous
2010-02-08 17:22:29