0

In C++ object constructors and destructors can be used to trace scopes during code execution, something like this:

#define TRACE(msg) Helper trace_helper(msg);
class Helper {
    const char* _name;
    Helper(const car* name) {
        _name = name;
        printf(“enter %s”, name);
    }
    ~Helper() { printf(“exit %s”, _name); }
};

This allows me to trace my code, like for example

main() {
TRACE(“main”)
    for(...) {
         foo();
     }
}

void foo() {
    TRACE(“foo”)
     do some stuff
     if(condition) {
         TRACE(“inner block”)
          do some stuff
     }
}

This is useful to profile code for example.

Now, not having constructors and destructors available in C, i wonder if it’s still possible to create a TRACE macro that takes a single line and will also trace the exit of the scope?

matthias_buehlmann
  • 4,641
  • 6
  • 34
  • 76
  • write a macro for such stuff https://stackoverflow.com/questions/368385/implementing-raii-in-pure-c – fas Oct 12 '19 at 10:59
  • Is it acceptable to create a pre-build step to do some magic before the code is actually built? If so, I'd just replace all `{` and `}` with some code that logs the blocks. – Martin B. Oct 12 '19 at 11:03
  • 1
    @MartinB. That sounds like a good idea, how would you create a pre build event that locates `{ }` ? – Irelia Oct 12 '19 at 22:32

1 Answers1

1

What you are asking for is not possible in standard C; but depending on your compiler there might be an attribute for it. In GCC the cleanup attribute can probably do what you want

#include <stdio.h>
void tracemsg(void* ctx){
    printf("scope exit\n");
}
#define SCOPE_CHECK \
    void* ctx __attribute__((cleanup (tracemsg)));

int main(){
    {
        SCOPE_CHECK;//gets printed last
        printf("in scope\n");
        printf("in scope\n");
        printf("in scope\n");
        printf("in scope\n");
    }
}
Irelia
  • 3,407
  • 2
  • 10
  • 31