Reputation:
I have to different files : main.c and source.c. I want to scanf and printf information in main.c file, but to work with structure in source.c. I don't know how to use structure in another file without using headers. I've tryied to use extern, but that was totally wrong.
Can you teach me how to use extern when we talk about structure
For example (just example)
main.c
typedef struct Node{
int n;
int p[22];
int z[33];
}Node;
Node a;
void sum (int i,int j, Node *sum);
main(){
int i,j;
scanf("%d",&i);
scanf("%d",&J);
sum (i,j,&a)
printf("%d",a.k);
return 0;
}
source.c
extern Node a;
void sum (int i,int j, Node *sum){
a.n = i+j;
}
Upvotes: 0
Views: 244
Reputation: 26703
I am going to ignore the part that you do not want to use headers, because I suspect that is based on a misunderstanding.
You need to do the declaring and the typedefs in a header, using extern
(if necessary, but globals are discouraged anyway).
The using and any definitions are in .c files, which #include
the headers.
main.c
/* remove this ... to header
typedef struct Node{
int n;
int p[22];
int z[33];
}Node;
*/
#include "myheader.h"
Node a;
/* remove this ... to header
void sum (int i,int j, Node *sum);
*/
int main(void) /* cleaner prototype */
{
int i,j;
scanf("%d",&i);
scanf("%d",&J);
sum (i,j,&a)
printf("%d",a.n); /* I use n instead of k, because I do not see that... */
return 0;
}
source.c
/* remove this ... completely
extern Node a;
*/
#include "myheader.h"
void sum (int i,int j, Node *sum){
sum->n /* not sure where the k was meant to be */ = i+j;
/* use the parameter pointer, use -> */
}
myheader.h
typedef struct Node{
int n;
int p[22];
int z[33];
}Node;
void sum (int i,int j, Node *sum);
Note, I agree with Darth-Codex, that global variable is unneeded here (because the pointer parameter provides all needed access) and that a cleaner main()
prototype should be used (and whatever else I may find....). And that means that the global could better be replaced by a main-local.
Upvotes: 1