编写一个 C++ 函数以对外部声明的数组进行操作

Writing a C++ function to operate on arrays declared externally

本文关键字:声明 对外部 数组 操作 函数 C++ 一个      更新时间:2023-10-16

我正在尝试编写一组C++函数(a.ha.cpp(,这些函数在数组上实现各种操作。实际的数组将在其他文件中定义(b.hb.cppc.hc.cpp等(。

我的目标是任何项目都可以在该项目中定义的数组上#include "a.h"和运行这些函数。我不想在a.h本身中包含任何内容,因为我希望任何未来的项目都能够在不重写的情况下使用a.h。但是,我不知道如何使用extern来做到这一点。

这是我目前拥有的一个玩具示例。 a实现了一个函数f,用于一个尚未指定的数组。

A.H

// 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();

答.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;

乙.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

我读了这些其他相关的问题:

  • 用常数初始化数组不起作用
  • 使用多个文件时,"数组绑定不是 ']' 标记之前的整数常量"
  • 为什么"extern const int n;"不能按预期工作?

。但我看不出如何将解决方案应用于我的情况。问题是通常人们最终会#include定义数组的文件,我想反过来做:在新项目中定义数组,并#include共享函数集以对该数组进行操作。


编辑1:如果我按照@id256的建议,将a.h中的array声明替换为以下内容:

extern int array[];

然后我得到一个不同的错误:

multiple definition of `ARRAY_LEN'

编辑2:我也尝试了以下答案:

为什么"extern const int n;"不能按预期工作?

基本上,我在b.h中添加了"extern const int int ARRAY_LEN",以"强制外部链接"。所以现在:

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 时,不需要指定大小(对于多维数组,除了第一维之外,您仍然需要所有内容(。只需使用:

extern int array[];

或者,在 a.h 中包含 b.h(在声明数组之前(,以便在声明数组时可以看到ARRAY_LEN的定义。