Analyn
Analyn

Reputation: 89

C Undefined reference

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;
}

Upvotes: 5

Views: 6498

Answers (5)

bph
bph

Reputation: 11268

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;
}

Upvotes: 0

log0
log0

Reputation: 10937

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.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409364

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.

Upvotes: 9

ams
ams

Reputation: 25599

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;
}

Upvotes: 3

hmjd
hmjd

Reputation: 122001

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.

Upvotes: 1

Related Questions