I'm trying to implement my own assert
macro in a C89 standard.
I want it to be exactly as the original one:
dir/file.c:20: MyFunction: Assertion `null != pointer` failed.
There are 2 problems:
__FUNC__
is available only since c99 standard.exit(1)
and __Exit(1)
but both of them are not working and I think it's because macros
are converted to code while the per-processing stage, which means the pre-processor doesn't even know what are these exit
functions yet. because they are relevant only in the compiler stage, right?Here's my code:
/********************************* Inclusions *********************************/
#include <stdio.h> /* printf, NULL */
/***************************** Macros Definitions *****************************/
#define ASSERT(expr) \
if (!(expr)){ \
fprintf(stderr, "%s:%d: Assertion `%s` failed.\n" \
,__FILE__, __LINE__, #expr); }
/******************************************************************************/
int main()
{
void *null_ptr = NULL;
ASSERT(NULL != null_ptr);
printf("ALL WORKS");
return (0);
}
/******************************************************************************/
my output is:
`file.c:25: Assertion `NULL != null_ptr` failed.`
Is there any way to get the function name or exit the program with a macro? Because right now, I'm not getting the function's name, and more important, the program isn't getting stopped even though the assert prints an error message.
And it's strange, because how it's not possible to get the function name or to exit a program with a macro but it is possible for the original assert
to do both of these?
P.S the __FILE__
per-identifier prints for me only the file name, as file.c
and not dir/file.c
as the original assert
does. Why is that?
I wish I could write something like:
#define ASSERT(expr) \
if (!(expr)){ \
fprintf(stderr, "%s:%d: %s: Assertion `%s` failed.\n" \
,__FILE__, __LINE__, __FUNC__, #expr); exit(1) }
Thanks.
Indeed, C89 doesn't have a way to get the function name. So if you can only rely on C89, you'll have to do without this. Note that many implementations may have provided their own extensions for this even before C99, and may have used those extensions in their own definitions of assert()
; e.g. GCC had __FUNCTION__
.
The standard assert()
macro calls abort()
if the assertion fails. So if you want to replicate its behavior, you can do the same.