这使得C模块变量访问为只读 [英] Making C module variables accessible as read-only

查看:125
本文介绍了这使得C模块变量访问为只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给一个模块变量客户端模块只读访问。
几种解决方案:

I would like to give a module variable a read-only access for client modules. Several solutions:

1 即可。最常见的一种:

1. The most common one:

// module_a.c
static int a;

int get_a(void)
{
    return a;
}

// module_a.h
int get_a(void);

这使得每个变量一个功能共享,一个函数调用(我想这两个执行时间和可读性),并为每读一个副本。假设没有优化连接程序。

This makes one function per variable to share, one function call (I am thinking both execution time and readability), and one copy for every read. Assuming no optimizing linker.

2 。另一种解决方案:

// module_a.c
static int _a;
const int * const a = &_a;

// module_a.h
extern const int * const a;

// client_module.c
int read_variable = *a;
*a = 5;  // error: variable is read-only

我喜欢,除了客户端需要读取指针的内容的事实。此外,每隔只读变量需要它的extern常量指针常量

3 。第三种解决方案,通过第二个启发,是隐藏一个结构和一个外部指向struct背后的变量。记号 module_name-方式> A 是客户端模块中更具可读性,在我看来

3. A third solution, inspired by the second one, is to hide the variables behind a struct and an extern pointer to struct. The notation module_name->a is more readable in the client module, in my opinion.

4 。我能为 get_a(无效)函数来创建的内联定义的。它仍然看起来像客户端模块中的一个函数调用,但优化应该发生。

4. I could create an inline definition for the get_a(void) function. It would still look like a function call in the client module, but the optimization should take place.

我的问题:


  • 有没有办法使只读在其他模块访问的模块修改的变量最好的方法?在哪方面最好?

  • Is there a best way to make variables modified in a module accessible as read-only in other modules? Best in what aspect?

你会接受或拒绝使用,且上述解决方案,为什么?

Which solutions above would you accept or refuse to use, and why?

我知道,这是microoptimization - 我可能不会实现它 - 但我仍然有兴趣的可能性,首先在明知

I am aware that this is microoptimization - I might not implement it - but I am still interested in the possibility, and above all in the knowing.

推荐答案

关于第4个选项,我不知道你可以把它内联如果变量是不是实现文件外部访问。我也不能算作真正的只读选项#2,#3。指针可以有常量性抛弃和被修改(常量只是一个编译器的警告,四大皆空)。唯一的选择#1是只读的,因为它返回一个副本。

Concerning option #4, I'm not sure you can make it inline if the variable isn't accessible outside the implementation file. I wouldn't count options #2 and #3 as truly read-only. The pointer can have the constness cast away and be modified (const is just a compiler "warning", nothing concrete). Only option #1 is read-only because it returns a copy.

这篇关于这使得C模块变量访问为只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆