Array problem

H

hepp

I have a header file that contains some constans, and the following
lines are included in it:

const int a[] = {1};
const int b[] = {2};
const int* c[] = {a, b};

My code compiles, but the linker complains about that "c" is multiple
declared. It seems to have been defined in all source files that
included this header file. Why? It only seems to be a problems when
using arrays - the following code links without any problems:

const int a = 1;
const int b = 2;
const int c = a + b;

The result is the same for all compilers I have tried (gcc and Visual
Studio).
 
M

Mike Wahler

hepp said:
I have a header file that contains some constans, and the following
lines are included in it:

const int a[] = {1};
const int b[] = {2};
const int* c[] = {a, b};
My code compiles, but the linker complains about that "c" is multiple
declared.

It is.

That's because you've apparently #included this header
in more than one source file of your project. So you've
effectively defined the same object more than once (look
up the 'one definition rule'). The definitions of 'a' and
'b' are OK, because they're const. The array 'c' is not
const, only what the pointers point to are const.
It seems to have been defined in all source files that
included this header file.
Yes.

Why?

Because you wrote it that way.

Try:

const int * const c[] = {a, b};

This makes the array itself const, as well as the
pointed-to ints.
It only seems to be a problems when
using arrays

The problem is not unique to arrays. It's the same
as if you'd tried to #include:

int i = 42;

in more than one source file of the same project.
- the following code links without any problems:

const int a = 1;
const int b = 2;
const int c = a + b;

That's because all the objects are const. Your
array above is not.
The result is the same for all compilers I have tried (gcc and Visual
Studio).

Then they are all correctly diagnosing an error.

-Mike
 

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

Forum statistics

Threads
474,176
Messages
2,570,950
Members
47,503
Latest member
supremedee

Latest Threads

Top