【发布时间】:2024-01-16 00:07:01
【问题描述】:
我正在尝试编写一组 C++ 函数(a.h、a.cpp)来实现对数组的各种操作。实际的数组将在其他文件中定义(b.h、b.cpp、c.h、c.cpp 等)。
我的目标是任何项目都可以#include "a.h" 并在该项目中定义的数组上运行这些函数。我不想在a.h 本身中包含任何内容,因为我希望未来的任何项目都能够使用a.h 而无需重写它。但是,我不知道如何使用extern 来做到这一点。
这是我目前所拥有的玩具示例。 a 实现了一个函数 f,用于一个尚未指定的数组。
啊。
// this is not right, but I'm not sure what to do instead
extern const int ARRAY_LEN;
extern int array[ARRAY_LEN]; // error occurs here
void f();
a.cpp
#include "a.h"
// Do something with every element of "array"
void f() {
for(int i=0; i < ARRAY_LEN; i++) {
array[i];
}
}
现在,项目b 定义了数组,并希望在其上使用函数f。
b.h
const int ARRAY_LEN = 3;
b.cpp
#include "a.h"
#include "b.h"
int array[ARRAY_LEN] = {3, 4, 5};
// Some functions here will use f() from a.cpp
当我编译这个时,我得到:
In file included from b.cpp:1:0:
a.h:2:27: error: array bound is not an integer constant before ‘]’ token
我阅读了其他相关的问题:
- initialize array with constant number does not work
- "array bound is not an integer constant before ']' token" when using multiple files
- Why does "extern const int n;" not work as expected?
...但我看不到如何将解决方案应用于我的案例。问题是通常人们最终会#include-ing 定义数组的文件,而我想反过来做:在新项目中定义数组,#include 要操作的共享函数集在那个数组上。
编辑 1:如果我按照 @id256 的建议将 a.h 中的 array 声明替换为以下内容:
extern int array[];
然后我得到一个不同的错误:
multiple definition of `ARRAY_LEN'
编辑 2:我也尝试了以下答案:
Why does "extern const int n;" not work as expected?
基本上,我将“extern const int ARRAY_LEN”添加到b.h 以“强制外部链接”。所以现在:
b.h
extern const int ARRAY_LEN;
const int ARRAY_LEN = 3;
.. 和所有其他文件与原来的相同。但我得到了同样的原始错误:
a.h:2:27: error: array bound is not an integer constant before ‘]’ token
【问题讨论】:
-
那么声明
extern int array[]有什么问题? -
这应该通过将数组作为参数传递给函数来完成;不是通过使用全局变量。
-
使用
std::vector并通过引用参数传递数组或向量。
标签: c++ arrays constants extern linkage