繁体   English   中英

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

[英]Writing a C++ function to operate on arrays declared externally

我正在尝试编写一组实现数组上各种操作的C ++函数( aha.cpp )。 实际的数组将在其他文件( bhb.cppchc.cpp等)中定义。

我的目标是任何项目都可以#include "ah"并在该项目中定义的数组上运行这些功能。 我不想在ah本身中包含任何内容,因为我希望将来的任何项目都可以使用ah而无需重写它。 但是,我不知道如何使用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

BH

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

我阅读了以下其他相关问题:

...但是我看不到如何将解决方案应用于我的案子。 问题是通常人们最终会#include include-添加用于定义数组的文件,而我想以另一种方式来做:在新项目中定义数组,然后#include在该项目上操作的共享函数集数组。


编辑1:如果我更换的声明arrayah用下面,通过@的建议id256:

extern int array[];

然后我得到另一个错误:

multiple definition of `ARRAY_LEN'

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

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

基本上,我在bh中添加了“ extern const int ARRAY_LEN”,以“强制外部链接”。 所以现在:

BH

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[];

或者,在ah中添加bh(在声明数组之前),以便在声明数组时可见ARRAY_LEN的定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM