简体   繁体   English

我可以将const限定符应用于全局变量以使用选择性函数吗?

[英]Can I apply const qualifier to global variable for selective functions?

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? 是否可以对某些功能(在同一转换单元内)“应用promise”,即g_var_1应该被视为它们的只读全局变量? 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; 错误:“ g_var_1”外部常量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: 从本质上讲,我想限制在更复杂的代码中意外修改全局变量的可能性(real的值在编译时是已知的),但仍不能“钩住”它们作为函数的参数,例如:

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

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. 然后,您可以添加getter函数以暴露其值,而无需将其暴露于模块外部的修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM