#cannot access a variable using extern

9 messages · Page 1 of 1 (latest)

queen dew
#

when i use extern to get a variable 'a' from another file in the same project folder it shows an error: undefined reference to `a'.
can someone explain why is that and what is the solution for it?


int main(int argc, char const *argv[])
{

  
extern int a;
printf("%d",a);


  return 0;
}``` 
```#include <stdio.h>


int main(int argc, char const *argv[]) {

  int a=5;


  return 0;
}```
blissful forge
#
> clang -c foo.c
> clang -c main.c
> clang foo.o main.o -o main.exe
> main.exe
5
#

I'm fairly certain the definition of int a = 5; for example needs to be in the global scope.

#

Also your program won't compile with two main functions most likely.

queen dew
blissful forge
#

I was able to compile it.

#

How are you compiling @queen dew

queen dew
# blissful forge I was able to compile it.

i use an IDE so i just use the f5 key .
but someone showed me how to compile two files at once and i had to get rid of the parameters that i had in the main function and it worked.
gcc .\main.c -o main.exe .\other.c -Wall -Wextra -Werror -pedantic; .\main.exe