编写一个 C++ 函数以对外部声明的数组进行操作
Writing a C++ function to operate on arrays declared externally
我正在尝试编写一组C++函数(a.h
,a.cpp
(,这些函数在数组上实现各种操作。实际的数组将在其他文件中定义(b.h
、b.cpp
、c.h
、c.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
的定义。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- c++类声明时,相同的例程,不同的成员变量类型
- 编写一个 C++ 函数以对外部声明的数组进行操作