繁体   English   中英

外部常数

[英]externally constant variable

我在一个文件中定义了一个变量,该变量可以由文件本身中的代码操纵,但是对于任何外部文件而言,它始终是恒定值。

我如何将变量声明为常量,而又不会在为其定义文件的内部赋值时引发错误,同时允许编译器优化其读取,就好像它们在这些外部单元中是常量一样?

右值无法修改。 使用访问器函数进行访问可确保您仅提供右值,例如

static int value;

extern int getconst();

int getconst() {
  return value;
}

这使得:

getconst() = -1; // Compiler error

另外,您可以通过指向const intconst指针公开您的值:

#include <stdio.h>

static int value = -1;

extern const int * const public_non_modifiable;
const int * const public_non_modifiable = &value;


int main() {
  printf("%d\n", *public_non_modifiable); // fine
  *public_non_modifiable = 0; // compiler error
  return 0;
}

在修改virables的文件中声明如下:

int e = 0, e_ant = 0, adj;

并以这种方式在其他文件中声明:

extern const int e, e_ant, adj;

为我工作。 我将dsPIC与MPLAB一起使用。

第一个文件计算所有变量的值。 第二个文件仅在LCD显示屏上显示这些值,并且完全禁止写入此变量。

暂无
暂无

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

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