简体   繁体   English

外部常数

[英]externally constant variable

I have a variable defined in one of my files, It may be manipulated by the code in the file itself, but it is always a constant value to any external file. 我在一个文件中定义了一个变量,该变量可以由文件本身中的代码操纵,但是对于任何外部文件而言,它始终是恒定值。

How do i declare the variable as constant without raising errors on assigning this variable a value inside the file it is defined in while allowing compiler to optimize it's read as if it is a constant in those external units ? 我如何将变量声明为常量,而又不会在为其定义文件的内部赋值时引发错误,同时允许编译器优化其读取,就好像它们在这些外部单元中是常量一样?

A rvalue can't be modified. 右值无法修改。 Use an accessor function to access it guarantees you only offer an rvalue, eg 使用访问器函数进行访问可确保您仅提供右值,例如

static int value;

extern int getconst();

int getconst() {
  return value;
}

This makes: 这使得:

getconst() = -1; // Compiler error

Alternatively you can expose your value via a const pointer to a const int : 另外,您可以通过指向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;
}

Declaring in the file that modifies the virables as follows: 在修改virables的文件中声明如下:

int e = 0, e_ant = 0, adj;

and declaring in the other files in this way: 并以这种方式在其他文件中声明:

extern const int e, e_ant, adj;

works for me. 为我工作。 I am using a dsPIC with MPLAB. 我将dsPIC与MPLAB一起使用。

The first file computes the value of all the variables. 第一个文件计算所有变量的值。 A second file only shows those values in a LCD Display, with a totally forbiden writing of this variables. 第二个文件仅在LCD显示屏上显示这些值,并且完全禁止写入此变量。

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

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