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:
- There is no option to print the function name because the pre identifier
__FUNC__
is available only since c99 standard. - I don't know how to exit the program. I tried
exit(1)
and__Exit(1)
but both of them are not working and I think it's becausemacros
are converted to code while the per-processing stage, which means the pre-processor doesn't even know what are theseexit
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.