关于extern和const组合的变量的问题

Question about variables with combination of extern and const

本文关键字:变量 问题 组合 const extern 关于      更新时间:2023-10-16

我在互联网上搜索了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