Linking an array of const pointers

B

Ben Bacarisse

I have an array (much messier than this cut-down example) that I want to
hive off into another source file, but the two compiled files won't
link:

m.cc:
extern int *const table[];

int main()
{
return *table[0];
}

t.cc:
static int t1[] = { 1, 2, 3 };
static int t2[] = { 2, 3, 4 };

int *const table[] = { t1, t2 };

g++ says:

$ g++ -std=c++98 -pedantic m.cc t.cc
/tmp/ccniFOW7.o: In function `main':
m.cc:(.text+0x7): undefined reference to `ns::table'
collect2: ld returned 1 exit status

It works as one file where the content of t.cc follows main in m.cc. It
also work if I simply remove the "const" in t.cc.

What's going on?
 
M

Marc

Ben said:
I have an array (much messier than this cut-down example) that I want to
hive off into another source file, but the two compiled files won't
link:

m.cc:
extern int *const table[];

int main()
{
return *table[0];
}

t.cc:
static int t1[] = { 1, 2, 3 };
static int t2[] = { 2, 3, 4 };

int *const table[] = { t1, t2 };

g++ says:

$ g++ -std=c++98 -pedantic m.cc t.cc
/tmp/ccniFOW7.o: In function `main':
m.cc:(.text+0x7): undefined reference to `ns::table'
collect2: ld returned 1 exit status

It works as one file where the content of t.cc follows main in m.cc. It
also work if I simply remove the "const" in t.cc.

What's going on?

const variables, unless you put "extern" in front, have internal linkage. For an array, I guess that array of const counts as const...
 
B

Ben Bacarisse

Marc said:
Ben said:
I have an array (much messier than this cut-down example) that I want to
hive off into another source file, but the two compiled files won't
link:

m.cc:
extern int *const table[];

int main()
{
return *table[0];
}

t.cc:
static int t1[] = { 1, 2, 3 };
static int t2[] = { 2, 3, 4 };

int *const table[] = { t1, t2 };

g++ says:

$ g++ -std=c++98 -pedantic m.cc t.cc
/tmp/ccniFOW7.o: In function `main':
m.cc:(.text+0x7): undefined reference to `ns::table'
collect2: ld returned 1 exit status

It works as one file where the content of t.cc follows main in m.cc. It
also work if I simply remove the "const" in t.cc.

What's going on?

const variables, unless you put "extern" in front, have internal
linkage. For an array, I guess that array of const counts as const...

Ah, right. Thank you. I was aware of the linkage of consts, but I had
got the idea that the qualifications of the array type were distinct from
those of its elements. It makes sense (now!) that an array whose
elements are const is, in effect, const itself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,965
Messages
2,570,148
Members
46,710
Latest member
FredricRen

Latest Threads

Top