Search code examples
cheaderglobal-variablesextern

Error while referencing into a global variable using multiple files


These are my code files:

header.h

#ifndef HEADER_H
#define HEADER_H
extern int bar;
#endif

foo.c

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

void foo(void) {
    printf("foo: bar = %d\n", bar);
    printf("foo: ++bar = %d\n", ++bar);
}

main.c

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

int main(void) {
    int bar=0;

    printf("main: bar = %d\n", bar);
    printf("main: ++bar = %d\n", bar);

    foo();

    return 0;
}

When I try to compile those in Ubuntu:

gcc -c foo.c
gcc main.c foo.o -o program

I get this error from the linker:

/tmp/ccWHhwtm.o: In function `foo':
foo.c:(.text+0x6): undefined reference to `bar'
foo.c:(.text+0x1d): undefined reference to `bar'
foo.c:(.text+0x26): undefined reference to `bar'
foo.c:(.text+0x2c): undefined reference to `bar'
collect2: error: ld returned 1 exit status

As I have seen from other answered questions here, in order to share a global variable to multiple files, you will just have to declare the variable in the header file using extern keyword and define it in one of the .c codes. That is what I have done here, but I get this error.

What is happening ?


Solution

  • bar should be defined in file scope:

    #include <stdio.h>
    #include "header.h"
    
    int bar=0;
    
    int main(void) {
    ....