tags:

views:

649

answers:

2

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
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
You will need something like #ifndef FILE_H #define FILE_H [contents of file.h] #endifAround file.h
Richo
Have my last upvote for today, but you should take Richo's suggestion. @Richo, the term for that is an "include guard."
Chris Lutz
@Richo,Chris: Thanks.
codaddict
Thanks Richo for your comment.
Arman
No probs all, I learned something new as well :)
Richo
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