Re: Questions about const
gw7rib@aol.com wrote:
I was having linking errors when I put:
const LPCTSTR Main_window_name = _TEXT("Thingy_main_window");
in one file and
extern const LPCTSTR Main_window_name;
in another. I've since realised that this is because (in C++) consts
do not, by default, have external linkage. I've solved the problem by
inserting an "extern" in front of the first one. (LPCTSTR is
typedef'ed in the headers somewhere as a pointer to constant
"characters", and _TEXT is a macro to convert a string to the correct
form of characters.)
However, I still have a couple of nagging doubts. The first is, is it
OK to use consts both in and with typedefs? For instance, if I do:
typedef int i;
typedef const int ci;
then can I do whichever I choose of
const i b = 3;
and
ci c = 3;
to get a variable of type const int? I see from testing that
const ci d = 3;
is an error - including the consts twice.
The answer is "Yes, it's OK", and you've discovered it already,
haven't you?
My second question is that, normally, if one were to put "extern int
x;" in several files, you would need to also include a line "int x;"
in one of them. But with consts, it seems that every mention of them
can have the extern keyword. Is this correct?
The One Definition Rule has to be obeyed. Unless you initialise your
object, it's a declaration. Adding an initialiser converts your
statement into a definition. You need to have one and only one
definition for every object in your program.
Now, if all of your declarations of a built-in type object do not
have any initialisers, then they are all merely declarations and you
still need a definition (without the keyword "extern") unless you
add "= 0" to one of them.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask