A typical way to do it which ensures you use the same constant each time would be to use
const int someData = 768;
in one .cpp file, and in your header file (as hypheni says)
extern const int someData;
If you are seeing an error indicating that it's redefined, it seems strange. Can you post the error message, and the actual declarations & references to the const data?
Thank you for your help.
I did the same as you and hypheni said.
I declared "const int someData = 6" in header1.h
I declared "extern const int someData in main.cpp
The error is as follows:
I just checked with VC++ 6.0, doesn't seem to be any difference.
I think you described the files the wrong way round, you should use "extern" in the header file, and just declare it once in one of the .cpp files. That wouldn't explain the link error you described though, unless you're not including header1.h.
Can you check that you are declaring it as extern in the header?
const ints don't need to be externed, you can just put it in the header and be done with it.
a simple int though (non const) should be externed though, or you'll have multiple instances (of un-equal value).
Last edited by monarch_dodra; February 9th, 2011 at 05:29 AM.
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
I read this is a difference between C & C++, consts at file-scope do not have external linkage in C++, but they did in C.
So in C++, if you want to define const int in your header, you could have:
const int someData = 43;
const int someData = 42;
As long as you don't include both headers, all will work well, and you can use different values for the constant depending on which header you include.
Of course, normally you would just want to use the same value throughout, so would define it once, in one header file.
If you declare it as "extern", then you can only define it once, and will have to use the same value throughout your program. However, choosing where to define it becomes tricky. If you do it in a header, you can only include it once, in one compilation unit, so you are better defining it in a .cpp file. However, for a constant that is used in many places, it may not be clear which .cpp file it should be defined in.