0

I get a compiler error when programming the following:

  • file1.cpp: declaring/defining of several variables
  • file1.cpp: defining a pointer array that is pointing to each of these variables -> this array shall be const (=always point to these variables)
  • file2.cpp: here I want to use the pointer array and use the variables it points to.
    //file1.cpp
    int a,b,c,d;
    int *const pa[4] = {&a, &b, &c, &d};

    //file2.cpp
    extern int *const pa[4];

when compiling it drops the error in file2.cpp:

undefined reference to `pa'

How to define that pointer array with constant pointers and use it in different source files?

Best regards :-)

0

1 Answer 1

1

A const variable has internal linkage by default. To get external linkage, add extern to the definition:

extern int *const pa[4] = {&a, &b, &c, &d};
Sign up to request clarification or add additional context in comments.

2 Comments

Or probably cleaner: Put the extern int *const pa[4]; declaration in a header and include it in both file1.cpp and file2.cpp. This avoids type mismatch.
Thank you. It's working now. Knowing this, after another 5min research I found, that what I did above is working with variables. Using a const always requires an extern even at the definition. Or as walnut mentioned to put it in a header.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.