wirrbel
wirrbel

Reputation: 3299

Plain C equivalent to Rust's unimplemented!() macros

Please note that this is not a question on C++, but on plain C

In Rust there is a handy macro unimplemented!() to let the runtime crash, to be used when a function is unimplemented.

I basically have resorted to assert (false) to emulate it in my C coding. Which doesn't work for release builds.

What I like about assert(false) over exit(-1) is that I end up in the debugger at the right spot.

I found Function not implemented macro? which looks good but the crash macro is not defined at least in my clang-gcc setup.

Upvotes: 2

Views: 298

Answers (2)

Lundin
Lundin

Reputation: 214770

"Magic number 139: SIGSEGV" is not very helpful... it essentially just means "oops your program crashed, here be bugs". So stay clear of abort() and signal.h.

Instead I'd cook together a custom macro, which you can then include in a header file etc.

For example:

#define STR_(s) #s
#define STR(s) STR_(s)

#define HCF(msg)                           \
    do {                                   \
        printf("Halt and catch fire! ");   \
        puts(msg);                         \
        printf("Function: ");              \
        puts(__func__);                    \
        puts("File: " __FILE__);           \
        puts("Line: " STR(__LINE__));      \
        assert(0);                         \
        exit(EXIT_FAILURE);                \
    }while(0)

Example output:

Halt and catch fire! Unimplemented function executed!
Function: some_unimplemented_function
File: /app/example.c
Line: 20

The assert(0) is only there in case you want to end up with the debugger there in debug build.

Upvotes: 0

Steve Friedl
Steve Friedl

Reputation: 4247

This is what the abort() function can be used for:

Ref: https://en.cppreference.com/w/c/program/abort

Upvotes: 3

Related Questions