简体   繁体   中英

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

I am trying to write a set of C++ functions ( ah , a.cpp ) that implement various operations on arrays. The actual arrays will be defined in other files ( bh , b.cpp , ch , c.cpp , etc.).

My goal is that any project can #include "ah" and run these functions on arrays defined in that project. I don't want to have to include anything in ah itself, because I want any future project to be able to use ah without rewriting it. But, I can't figure out how to use extern to do this.

Here's a toy example of what I have so far. a implements a function f , to be used on an as-yet unspecified array.

ah

// 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];
  }
}

Now, project b defines the array and wants to use the function f on it.

bh

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

When I compile this, I get:

In file included from b.cpp:1:0:
a.h:2:27: error: array bound is not an integer constant before ‘]’ token

I read these other questions which are related:

... but I can't see how to apply the solutions to my case. The problem is that usually people end up #include -ing the files that define the array, and I want to do it the other way around: define the array in a new project, and #include the shared set of functions to operate on that array.


Edit 1: If I replace the declaration of array in ah with the following, as suggested by @id256:

extern int array[];

Then I get a different error:

multiple definition of `ARRAY_LEN'

Edit 2: I also tried the answer from:

Why does "extern const int n;" not work as expected?

Basically, I added "extern const int ARRAY_LEN" to bh in order to "force external linkage". So now:

bh

extern const int ARRAY_LEN;
const int ARRAY_LEN = 3;

.. and all other files are the same as originally. But I get the same original error:

a.h:2:27: error: array bound is not an integer constant before ‘]’ token

When declaring an array as extern , you don't need to specify the size (for a multi-dimensional array, you still need all but the first dimension). Just use:

extern int array[];

Alternatively, include bh in ah (before declaring the array) so that the definition of ARRAY_LEN is visible when you declare the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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