Products > Programming
Compile time object contruction in C++
(1/1)
westfw:
Suppose that I have an object like a "command", which gets put together into a linked list, with each "object" containing a text string, a function pointer to the action routine for that command, and a pointer to the next command.
Then in C++, I can sprinkle these around my source code as appropriate a global objects, and the constructor can link them all together.
--- Code: ---class cmd_t {
private:
static cmd_t *head;
const char *text;
void *(*func)(char *);
cmd_t *next;
public:
cmd_t(const char *t, void*(*f)(char *)) {
text = t;
func = f;
if (head == NULL) {
head = this;
} else {
cmd_t *p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = this;
}
}
}
cmd_t add("add", add_f);
cmd_t sub("sub", sub_f);
cmd_t mul("mul", mul_f);
--- End code ---
Now, that's all stuff that COULD happen at compile time, I think. But it doesn't, even with "-Os -flto"
Is there any way to convince the gnu C++ compiler to MAKE it happen at compile time? Extra credit if things can be "const" enough to end up in flash on a microcontroller.
(I tried adding some const and static qualifiers in essentially random places, which resulted in behaviors ranging from "no change" to "compile errors."
(full compileable source attached.)
greenpossum:
Why not write a script in your preferred language to spit out a C file with a list of class instances and intialisations?
Navigation
[0] Message Index
Go to full version