5

I got some problem with the following codes particularly in header.c where i can't access the extern int x variable in header.h... Why? Does extern variable in .h not global? How can i use this on other files?

===header.h===

#ifndef HDR_H
#define HDR_H

extern int x;
void function();

#endif

===header.c===

#include <stdio.h>
#include "header.h"

void function()
{
    printf("%d", x); //****undefined reference to x, why?****
}

===sample.c===

int main()
{
    int x = 1;
    function();
    printf("\n%d", x);
    return 0;
}
Analyn
  • 89
  • 2
  • 9
  • 1
    possibly just remove the `int` before `x` in your main function. this would prevent a new local variable being created in the main function with the same name as the global variable – bph Aug 08 '12 at 09:08
  • (removed; accidentally added comment) – Michel Keijzers Aug 08 '12 at 09:13
  • See also more info about the extern int in [http://stackoverflow.com/questions/7610321/difference-between-extern-int-a-extern-int-a-42][1] [1]: http://stackoverflow.com/questions/7610321/difference-between-extern-int-a-extern-int-a-42 – Michel Keijzers Aug 08 '12 at 09:15

5 Answers5

9

The declaration

extern int x;

tells the compiler that in some source file there will be a global variable named x. However, in the main function you declare a local variable x. Move that declaration outside of main to make it global.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

The extern keyword say the variable exists but does not create it. The compiler expects that another module will have a global variable with that name, and the linker will do the right thing to join them up.

You need to change sample.c like this:

/* x is a global exported from sample.c */
int x = 1;

int main()
{
    function();
    printf("\n%d", x);
    return 0;
}
ams
  • 24,923
  • 4
  • 54
  • 75
1

extern declares a variable, but does not define it. It basically tells the compiler there is a definition for x somewhere else. To fix add the following to header.c (or some other .c file but only one .c file):

int x;

Note that in main() the local variable x will hide the global variable x.

hmjd
  • 120,187
  • 20
  • 207
  • 252
1

Indeed extern int x; means x will be defined in another place/translation unit.

The compiler expects to find a definition of x in the global scope somewherelse.

log0
  • 10,489
  • 4
  • 28
  • 62
0

I would reorganise/modify your code like this and get rid of header.c

===sample.h===

#ifndef SAMPLE_H
#define SAMPLE_H

extern int x;
void function();

#endif

===sample.c===

#include <stdio.h>
#include "sample.h"

int x;

void function()
{
    printf("%d", x);
}

int main()
{
    x = 1;
    function();
    printf("\n%d", x);
    return 0;
}
bph
  • 10,728
  • 15
  • 60
  • 135