Reputation: 77
source.c ::
int source=0;
int desti=0;
char str[50]="";
source.h::
extern int source;
extern int desti;
extern char str[50];
station1.c
#include"source.h"
#include<stdio.h>
main()
{
printf("%d %d",source,desti);
}
When I compile station1.c I get the following error:
undefined reference to 'desti'
undefined reference to 'source'
Could anyone please tell me where I have gone wrong?
Upvotes: 0
Views: 42
Reputation: 1181
When we use extern modifier with any variables it is only declaration i.e. memory is not allocated for these variable. Hence in your casecompiler is showing error unknown symbol source & desti. To define a variable i.e. allocate the memory for extern variables it is necessary to initialize the variables.
initialize the variables in source.c
or another way is to compile with combining the object file
gcc -c source.c station1.c -Isource.h
Upvotes: 0
Reputation: 7044
What did your compile command line look like?
Try:
cc -c station1.c -o station1.o
cc -c source.c -o source.o
cc -o a.out station1.o source.o
The first two compile the files by themselves and puts the result in a .o file.
The last line combines the .o files into an executable named 'a.out'.
Upvotes: 1