0

I made 2 files which are different from the program above one is temp1.h and another is temp2.c to understand how extern is used. So here is temp1.h

#include<stdlib.h>
typedef struct node * bond;
extern int jk;

and temp2.c is

#include<stdio.h>
#include<temp1.h>
struct node {
int data;
};
int main ()
{
bond t1;
t1=(bond)malloc(sizeof(bond));
t1->data=23;
printf("the data is %d\n",t1->data);
jk=0;
printf("The variable jk = %d\n",jk);
}

and when I compile these as cc -I ./ temp2.c then I get

/tmp/ccdeJCat.o: In function `main':
temp2.c:(.text+0x3c): undefined reference to `jk'
temp2.c:(.text+0x46): undefined reference to `jk'
collect2: ld returned 1 exit status

I had declared jk in temp1.h as an extern int so why can I not initialize it in temp2.c?

reality displays
  • 731
  • 3
  • 9
  • 18
  • 2
    This is basically the same question as the [previous one](http://stackoverflow.com/questions/4274190/warning-in-extern-declaration). If you need to clarify, please edit the question. – Matthew Flaschen Nov 25 '10 at 07:22
  • +1 to Matthew Flaschen, Why can't the previous question be edited? – Jay Nov 25 '10 at 07:33
  • See [SO 1433204](http://stackoverflow.com/questions/1433204/what-are-extern-variables-in-c) for an explanation of how to define and use global variables in C. – Jonathan Leffler Nov 25 '10 at 07:57

3 Answers3

2

There's no object file you've linked against that doesn't have it declared extern, so there's no definition.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2
int jk;

The above declaration must be made somewhere in the code. Also, jk must be global.

Donotalo
  • 12,748
  • 25
  • 83
  • 121
0

instead of #include <temp1.h>

replace with #include "temp1.h"

KillerFish
  • 5,042
  • 16
  • 55
  • 64
  • The angle brackets are for files in a particular hierarchy of the system (typically system headers). The quoted filenames are relative to the current directory. – UncleO Nov 25 '10 at 07:30