关于extern和const组合的变量的问题
Question about variables with combination of extern and const
我在互联网上搜索了const
+extern
,但似乎没有一个很好的答案来回答我的问题。
const
本身意味着内部链接,但如果我想在编译单元之间共享常量变量。extern
是最好的选择吗?
常见的解决方案是:
//g.h
extern const int MAX;
// g.c
extern const int MAX = 3;
然而,这种解决方案有一个缺点,如下所示:
// Say, I want to use this MAX in the same header file.
// g.h
extern const int MAX;
class AClass
{
public:
AClass (): i(MAX){}
private:
int i;
};
编译器会像这样抱怨:"错误C2057:需要常量表达式"。
有解决方案吗?
如果您希望能够在编译时使用常量(即,在不使用VLA的情况下,通过它来调整数组大小(,则必须在编译时知道它,即它不能具有外部链接。
然而,你可以在头文件中声明你的常量,并让它对包括它在内的任何人都可用。不过,这不会产生与外部链接完全相同的效果。
// a.h
const int MAX = 3;
// a.cpp
#include "a.h"
int b[a];
常数整数的一个简单解决方案是使用enums:
// g.h
enum { MAX = 3; }
// g.c
#include "g.h"
static char buf[MAX];
您将无法获取MAX
的地址,但反过来您可以以零内存成本获得该地址。
extern const int MAX;
int i[MAX];
做不到。你可以做一些类似的事情
const int MAX = ReadAnIntegerFromTheConsole();
完全有效和合法,但欢呼——不是一种持续的表达。
const
单独表示内部链接
这是不正确的,static
表示内部链接,const
只是说对象不能变异。尝试将变量声明为
extern static int foo;
编译器会抱怨链接冲突。要在翻译单元之间共享const
,请按照您的建议执行。
在标题中
extern const int MAX;
在源文件中
const int MAX = 10; // note you can omit the extern here
下面是一个可以解决您的问题的工作示例。总之,将数组大小定义为头文件中的常量。在另一个头文件中,将数组声明为extern
。在下面的示例中,我将数组引用为extern
,而不使用数组的include文件。
array_size.hpp
const unsigned int MAX_ARRAY_SIZE = 16;
array.cpp
#include "array_size.hpp"
int array[MAX_ARRAY_SIZE];
main.cpp
#include "array_size.hpp"
// Reference the array from array.cpp
extern int array[MAX_ARRAY_SIZE];
int main(void)
{
array[1] = 7;
return 0;
}
*array_size.hpp*文件定义了大小,通过包含标头,标识符可以在其他翻译单元中使用。
我在Cygwin上使用进行编译
g++ -I. -o array.exe main.cpp array.cpp
为什么不直接使用#define?
#define MAX 3
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++理解计算字符变量的问题
- 在通知提升间处理条件变量时未按住锁会导致问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 将十六进制值设置为用于填充的字符变量时出现问题
- 初学者问题:如何访问此变量?
- 关于仅正确使用二传手和变量的问题
- 为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?
- C++ 多线程中的锁和条件变量问题
- C++grpc的一些变量问题
- 我如何加载多个脚本而没有变量问题
- 未初始化的变量问题C++
- C++和引脚工具 - IF语句非常奇怪的双变量问题
- 如何通过引用捕获异常来解决局部变量问题
- sscanf写入变量问题
- 影子变量问题Qt
- C++ 中的局部变量问题
- 跨平台条件变量问题
- Makefile变量问题,make想要创建"*.o"而不是foo.o bar.o等
- c++变量问题