C Undefined Link

I am having a problem with the following codes, especially in header.c, where I cannot access the extern int x variable in header.h ... Why? Is extern variable in .h not global? How can I use this in 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;
}
+5
source share
5 answers

Announcement

extern int x;

tells the compiler that there will be a global variable with a name in some source file x. However, in a function, mainyou declare a local variable x. Move this ad outside mainto make it global.

+7
source

extern , , . , , , .

sample.c :

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

int main()
{
    function();
    printf("\n%d", x);
    return 0;
}
+3

extern , . , x - . header.c ( - .c, .c):

int x;

, main() x x.

+1

extern int x; , x / .

The compiler expects to find a definition xin a global scope somewhere.

+1
source

I would reorganize / modify my code 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;
}
0
source

All Articles