Common constants for an AVR / Linux GCC C++ project
I'm creating software for an Linux + AVR Arduino project. Obviously the whole work is split in several projects in Eclipse (I'm n开发者_如何学运维ot using Arduino IDE). I'd like to use common, mostly string, constants for all those projects. I also have to spare microcontroller's RAM so compile-time constants needed. How do I best implement it? My idea is to create a separate, header-only, project for those constants.
Using:
class A {
public:
static const char * const STRING;
static const unsigned char BOOL;
};
is not good enough, because I'd like to be able to concatenate string constants like this:
class A {
public:
static const char * const STRING_PART1;
static const char * const STRING_PART2;
static const unsigned char BOOL;
};
const char * const A::STRING_PART1 = "PART1_";
//const char * const A::STRING_PART2 = A::STRING_PART1 + "PART2"; //obviously won't compile
//const char * const A::STRING_PART2 = strcat("PART2", A::STRING_PART1); //this is not compile-time
I also don't want to use define
. I'd like to use:
class A {
public:
static const std::string STRING_PART1;
static const std::string STRING_PART2;
}
which allows for string concatenation and is (AFAIK) compile-time, but std::string is not available in avr projects - or I'm wrong here and just don't know how to use it.
Any help appreciated.
You can continue with the current idea of using const char* const
(if std::string
is not usable). I would suggest to use #define
for assignment purpose only. Example:
class A {
public:
static const char * const STRING_PART1;
static const char * const STRING_PART2;
static const unsigned char BOOL;
};
#define PART1_ "PART1_" // <--- for value assignent
#define PART2_ "PART2_"
const char * const A::STRING_PART1 = PART1_;
const char * const A::STRING_PART2 = PART1_ PART2_; // <--- ok! concatenation by compiler
Compile time for me means it is stored in ROM (eg. microcontroller's flash), where as runtime variables are stored in RAM. In my case, it's RAM I have to spare. The compiler decides where to put variables basing on many rules. Defines are one example of compile-time constants, they clearly don't count up to RAM usage. An other example should be static class constants - but in this case my compiler decides otherwise. Of course, I may be confusing things.
I think that you're in fact confusing things:
- defines are not stored in ROM - they are not part of your program at all as they get evaluated by the preprocessor already.
- the difference between "compile time" and "run time" you're making applies to evaluation, not storage.
If you want to use program memory (= AVR flash) for constant strings, use the PSTR macro from avr/pgmspace.h.
精彩评论