Steve4879
Steve4879

Reputation: 71

Where are variables stored when you have "global" variables in multiple C files?

When you have multiple C files, say main.c and process.c I was trying to understand where variables declared outside of functions in both cases are stored.

// this is main.c
#include <stdio.h>
#include "process.h"
int foo = 1;

void main() {
   int count = get_counter();
}

// this is process.c
#include <stdio.h>

int counter = 0;

int get_counter() {
    return counter;
{

So when you have two c files, your main.c and a process.c, you can call get_counter() in main.c and it will return the value from the process.c file. What I was trying to understand is where the compiler, or how it stores int foo in main.c and int count in process.c? Is this part of some data storage section? It is not on the stack right? It also seems having a separate process.c file makes it so it is not a global variable.

I have been really trying to understand how variables scope is handled and can get a little tricky for me. Does the #include "process.h" essentially compile as if you had the functions and their prototypes in the main.c above the rest of the code? To me that would make the int counter global so I know I am confusing something.

Thank you for taking your time to read this.

Upvotes: 0

Views: 807

Answers (1)

John Bode
John Bode

Reputation: 123458

That's a function of the executable file format, not the C language itself. For ELF (*nix and similar systems) and PE/COFF (Windows and similar), globals or other objects with static storage duration will be stored in either the .bss or .data sections depending on whether they're initialized or not. This is space allocated from within the program's binary image itself (not taken from the stack or heap).

Other executable file formats may use different section names.

Upvotes: 1

Related Questions