Reputation: 3586
I have a header file a.h which is included in 2 .c files a.c and b.c
a.h
#ifndef A_H_INCLUDE
#define A_H_INCLUDE
extern int g;
void chk(int f);
#endif
a.c
# include <stdio.h>
# include "a.h"
void chk(int f)
{
if(g==1) printf("\n CORRECT\n");
else printf("\n INcorrect::%d: \n",f);
}
b.c
# include <stdio.h>
# include "a.h"
int main()
{
int g;
printf("\n ENTER::");
scanf("%d",&g);
chk(56);
return 0;
}
On compiling the code it is giving me error
gcc a.c b.c a.h -o j
/tmp/ccEerIPj.o: In function `chk':
a.c:(.text+0x7): undefined reference to `g'
collect2: ld returned 1 exit status
I have already checked Variable declaration in a header file and i guess i am doing the same thing.
Any suggestion or pointer to problem in code will be appreciated.
Many thanks
Upvotes: 0
Views: 2852
Reputation: 477040
Add int g;
to the global scope of your a.c
file to provide a definition for the variable.
(In case you're wondering, the local variable inside your main()
function has no linkage, since it's an automatic variable at block scope. It has nothing to do with your problem.)
Upvotes: 3