全局常量不使用#define [英] global constants without using #define

查看:392
本文介绍了全局常量不使用#define的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我期待定义一组内存地址做为所使用的一堆.c文件在.h文件中的常量(我们是在C,而不是C ++)。我希望能够看到的名称的变量,而不是只看到在调试器中的十六进制地址...所以我想我目前拥有的#define语句转换为在全球范围常量。问题是,如果我将它们定义是这样的:

Ok, I'm looking to define a set of memory addresses as constants in a .h file that's used by a bunch of .c files (we're in C, not C++). I want to be able to see the name of the variable instead of just seeing the hex address in the debugger... so I want to convert the #defines I currently have into constants that are global in scope. The problem is, if I define them like this:

const short int SOME_ADDRESS  =  0x0010

然后我得到了可怕的多次声明的错误,因为我必须使用相同的.h多个.c文件。我想用一个枚举,但是这是行不通的,因为它默认为整数类型(这是我的系统上的16位...我需要有过的类型更好的控制)。

then I get the dreaded "multiple declarations" error since I have multiple .c files using this same .h. I would like to use an enum, but that won't work since it defaults to type integer (which is 16 bits on my system... and I need to have finer control over the type).

我想过把所有的地址在一个结构......但我没有办法(据我所知)设置在头文件结构的实例的默认值(我不想承担一个特定的.c文件首先使用结构和其他填充它。我很想在.h文件中定义的常量)

I thought about putting all the addresses in a struct... but I have no way (that I know of) of setting the default values of the instance of the structure in the header file (I don't want to assume that a particular .c file uses the structure first and fills it elsewhere.. I'd really like to have the constants defined in the .h file)

这似乎很简单,当我开始,但我没有看到界定在头文件中的全局可用短整型常量的一个好办法...任何人知道的方式做到这一点?

It seemed so simple when I started, but I don't see a good way of defining a globally available short int constant in a header file... anyone know a way to do this?

谢谢!

推荐答案

使用声明在头文件中的常量的extern

Declare the constants in the header file using extern:

extern const short int SOME_ADDRESS;

在任意一个,但只有一个, .C 文件中提供的定义是:

const short int SOME_ADDRESS = 0x0010;

这篇关于全局常量不使用#define的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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