Author Topic: Compile time object contruction in C++  (Read 151 times)

0 Members and 1 Guest are viewing this topic.

Offline westfw

  • Super Contributor
  • ***
  • Posts: 3237
  • Country: us
Compile time object contruction in C++
« on: April 27, 2020, 12:37:10 am »
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: [Select]
class cmd_t {
    static cmd_t *head;
    const char *text;
    void *(*func)(char *);
    cmd_t *next;

    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);

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.)

Offline greenpossum

  • Frequent Contributor
  • **
  • Posts: 291
  • Country: au
Re: Compile time object contruction in C++
« Reply #1 on: April 27, 2020, 12:50:44 am »
Why not write a script in your preferred language to spit out a C file with a list of class instances and intialisations?

Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo