1

Consider following source file:

#include <stdio.h>

int g_var_1;
int g_var_2;
// ...

void f1(void);
void f2(void);
// ...

int main(void)
{
    f1();
    f2();

    return 0;
}

void f1(void)
{
    // set the value of g_var_1
    g_var_1 = 100;
}

void f2(void)
{
    // read the value of g_var_1
    printf("%d\n", g_var_1);
}

// ...

Is it possible to "apply promise" for some functions (within the same translation unit) that g_var_1 should be considered as read-only global variable for them? I have tried with something like:

void f2(void)
{
    extern const int g_var_1; 

    // read the value of g_var_1
    printf("%d\n", g_var_1);
}

but this yields into:

error: conflicting type qualifiers for ‘g_var_1’ extern const int g_var_1;

Essentially I would like to restrict possibility of unintended modification of global variable in more complex code (values for real are known compile-time), still without "hooking" them as functions' paramaters, like as:

void f2(const int g_some)
{
    printf("%d\n", g_some); 
}

1 Answer 1

1

The appropriate way to do that is by separating your code into modules, and defining those globals as static, which will make them only module visible and will not export their symbol outside. You can then add a getter function to expose their value, without exposing them to modifications from outside the module.

Sign up to request clarification or add additional context in comments.

1 Comment

What I have also tried is to shadow them as const local variables, e.g. const int g_var_1 = ::g_var_1; (sneaky C++..), but I like internal linkage concept, as it's less error-prone (some of them might be missed, copy-paste in every black-listed function..).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.