Search code examples
cextern

I am trying to implement a code using 'extern' keyword, IDE: VS Code (using code runner...)


extrn.c

#include <stdio.h>

extern int var;

int main()
{
    printf("%d", var);
    return 0;
}

var.c

int var = 5;

I go to file extrn.c and I run the code and I get this:

undefined reference to `var'

and this is what my output is looking like:

[Running] cd "/home/buff/Documents/Coding/C/C_programming_NESO/" && gcc extrn.c -o extrn && "/home/buff/Documents/Coding/C/C_programming_NESO/"
/usr/bin/ld: /tmp/ccoKgi02.o: in function `main':
extrn.c:(.text+0xa): undefined reference to `var'
collect2: error: ld returned 1 exit status
[Done] exited with code=1 in 0.093 seconds

Solution

  • Compile your both C files together to fix this undefined reference error.

    For GCC
    gcc extrn.c var.c -o main
    
    For clang
    clang extrn.c var.c -o main