I have the following which I'm trying to set up to show the difference between a variable with global scope vs one with file/program scope:
// scope.c
#include<stdio.h>
int main(void)
{
printf("External: %d\n", external);
printf("Internal (static): %d\n", internal); // should error
}
// scope_other.c
int external = 7; // file scope, external linkage
static int internal = 6; // file scope, internal linkage
And to compile with:
$ gcc scope.c scope_other.c -o scope && ./scope
But it seems like I'm missing something here to properly demonstrate the global vs static linkage. What would be the proper way to demonstrate this?
You need to have declarations of both variables in scope.c
.
Try adding extern int external, internal;
in scope.c
before the definition of main
. This will fix the compiler errors you're undoubtedly seeing for both variables. But you will still get a linker error for internal
only. If you comment out the line that prints internal
, but leave the line that prints external
alone, the program will compile, link and run.