I am a java developer, but I have had to learn C++ recently and I am confused about some things. What I would like to do is create a ‘global’ header file, which has a list of #define variables which will be constant throughout the suite I am creating. I created the header file, and I added some variables
#ifndef CONSTANTS_H
#define CONSTANTS_H
#define SM_START 1001;
#define SM_PAUSE 1002;
#define SM_STOP 1003;
#define SM_SAVE 1004;
#define SM_DISCARD 1005;
#define SM_SETUP 1007;
#endif // CONSTANTS_H
My problem is that I can’t access these…
I have included the header file where I need it, but there is no way for me to access the constants inside of it. Do I Have to have a .cpp file? is there a way for me to access the constant variables?
First: You shouldn’t put the semicolons at the end of the
#define.#defineis a preprocessor directive, meaning that it basically does text replacement of the defined name with the content. So if you do something likeint a = SM_STOP + 1;it would be preprocessed toint a = 1003; + 1;with your code, which is not what you want.Second: Headers are generally not compiled themselves but only for inclusion into
*.cppfiles or other headers (where#includeis once again a text substitution). Therefore, yes you need to have a.cppfile somewhere (well not exactly, first of all you can choose a different extension and second you could even give the compiler a header as compile unit, but I would advise against it, at least until you know what you are doing). However you do not need to have a.cppfile for your constants, just#includeyour header into whatever file you want to use the constants in.Third: Why are you using preprocessor defines here? This seems to be like a perfect job for an enum. Then you could put it into a namespace/struct for removing the need to prefix them (with
SM_). Or you could just use C++11’s newenum class, which behaves much like java’s enums. I would avoid preprocessors wherever possible. Since it is simply text replacement and it doesn’t respect any scoping and such, which makes it easy to get into problems (like with your semicolons).