Const Char* troubles

Started by
5 comments, last by Turtlebread 22 years, 7 months ago
This line in a header file: const char *WINDOW_NAME = "Main Window"; is giving me a linker error. Its telling me that its already been defined in a file. I have several other conts in that header, and none of them cause any problems. It is only the const char*. I have tried cleaning and rebuilding all, but no go. Whats up with this? -Chris
Advertisement
quote:Original post by Turtlebread
Its telling me that its already been defined in a file.


What file? If you have the declaration in both a header and an implementation file then you''ll have this kind of error. Look up the extern keyword.
If you''re trying to define it like other global constants, you will also want to make the pointer constant.

const char* const WINDOW_NAME = "Main Window";
quote:Original post by Oluseyi


What file? If you have the declaration in both a header and an implementation file then you''ll have this kind of error. Look up the extern keyword.


Its just defined in the header file. Then, when I compile, the linker error states that the const WINDOW_NAME has already been defined in the first .cpp file compiled. I do have inclusion guards, and other consts(ints for example)work fine.

All I was doing was changing my #defines to consts. This:
#define WINDOW_NAME "Main Window"
works fine...its just the const char*. The double const doesn''t fix it either.

-Chris

If you include the header inte multiple source-files, then you are in effect defining the variable in each source-file. Then the linker complains because you have multiple definitions with the same name.

The thing to do is to have this in the header:

extern const char *WINDOW_NAME;

and the following in exactly *one* source file:

const char *WINDOW_NAME = "Main Window";

This goes for all variables that must be accessible from many different source-files.

Redleaf is correct. "const char* WINDOW_NAME..." declares a variable that can point at const chars, but you can still assign to WINDOW_NAME because the pointer itself isn''t const. Adding the second const -- "const char* const WINDOW_NAME..." -- makes the pointer constant, thus allowing it to be added to a header.
The second CONST idea helped. I had to define it like this:

char* const WINDOW_NAME = "Main Window";

Thanks for your help everyone.

-Chris



Edited by - Turtlebread on October 3, 2001 6:34:41 PM

This topic is closed to new replies.

Advertisement