Search code examples
cfunctionglobal-variablesheader-files

Accessing a variable outside a c file


I'm trying to do this code, and I split it up into .c files (lets say file1.c and file2.c) and file1.h file. I'm not allowed to change which parameters I can send to the function, so I need to find another way to "send"/access another variable. I tried to make the variable static in the header file file1.h, and include it in the file2.c. The function in file1.c look something like this:

int function(int *array, int a, int b){
        ...
        ...
    if(global_variable == 1){
        point = array[(a+b)/2];
    }else if(global_variable == 0){
        point = array[b];
    }
    

and in the file2.c I have a function something like this:

double function2(t_sort_funcp fun, const case_t c, int array_length, result_t *buf, t_generate_array_funcp g_array){
    int array[array_length];
    switch (c)
    {
    case first:
        global_variable = 1;
        g_array(array, array_length);
        return debugg(fun, array, array_length);
        break;
    case second:// Wors case is an inverted sorted array.
        global_variable = 0;
        g_array(array, array_length);
        return debugg(fun, array, array_length);
        break;
    case third:
        global_variable = 1;
        g_array(array, array_length);
        return debugg(fun, array, array_length);
        break;
    }
    return 0;
}

In the file1.h I have:

#ifndef ALGORITHM_H
#define ALGORITHM_H

#include <stdbool.h> // bool
static int global_variable;

#endif

as you can see, I'm trying to change the global_variable variable in file2.c and use it in file1.c but that does not work, the if-statement in file1.c always executes the code in the else-statement, even if I changed the variable to 1. NOTE: file2.c always executes before file1.c


Solution

  • Do it the opposite way

    #ifndef ALGORITHM_H
    #define ALGORITHM_H
    
    #include <stdbool.h> // bool
    extern int global_variable;
    
    #endif
    

    In one of the .c files

    int global_variable;
    

    Include the .h file in all files which require access to this variable.

    static in global scope makes the variable only available in one compilation unit (file).