cvisual-studio-codeexternundefined-reference

Undefined reference variable using extern keyword


I have two C files in the same folder:

file1.c

#include <stdio.h>

int a;

int main()
{
    a = 1;
    printf("%d",a);
    return 0;
}

file2.c

#include <stdio.h>

extern int a;

int main()
{
    a = 1;
    printf("%d",a);
    return 0;
}

I run file2.c on vscode and its return:

C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe:C:\Users\Duong\AppData\Local\Temp\cc8Tiaj4.o:file2.c:(.rdata$.refptr.a[.refptr.a]+0x0): undefined reference to `a'
collect2.exe: error: ld returned 1 exit status

I have try many way sincluding add header file, but it doesn't work at all.

Can someone tell me if my code or my compiler has any problem


Solution

    1. You need to compile and link both files.
    2. You can't have two functions with the same name. As you have main function defined in both files it proves that you do not link them together.

    file1.c

    #include <stdio.h>
    
    int a;
    

    file2.c

    #include <stdio.h>
    
    extern int a;
    
    int main()
    {
        a = 1;
        printf("%d",a);
        return 0;
    }
    

    Then compile and link them from command line

    gcc -o main file1.c file2.c
    

    Visual studio code is not for a very beginners as it requires some configuration and understanding how thing work.

    Install Eclipse CDT which manages the projects for you without problems