Search code examples
c++arraysconstantsexternlinkage

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


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

My goal is that any project can #include "a.h" and run these functions on arrays defined in that project. I don't want to have to include anything in a.h itself, because I want any future project to be able to use a.h 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.

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

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.

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

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 a.h 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 b.h in order to "force external linkage". So now:

b.h

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

Solution

  • 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 b.h in a.h (before declaring the array) so that the definition of ARRAY_LEN is visible when you declare the array.