Reputation: 75
I am trying to do a debug mode for my program that writes something like this in one file to store the logs:
[Day Month D HH:MM:SS YYYY] foo.c function_name line 33: The thing that happens
The problem is know the exactly value of the line, obviously I can see it in my IDE, but I want to know if exist a more elegant and efficient way.
I hope you have explained me well (sorry if not) and thanks in advance.
Upvotes: 0
Views: 268
Reputation: 20141
You may have a look at macro assert
(assert.h
) where it is done as intended by you.
In short:
It has to be a macro. If it were a function it would report the file and line of this function but actually you would want the file and line where the function is called. (This does not mean that this macro cannot call a function as helper.)
The current file and line are accessible by the macros __FILE__
and __LINE__
.
So this is how it could look in source code:
#define LOG_DEBUG(TEXT) log_debug(__FILE__, __LINE__, TEXT)
void log_debug(const char *file, int line, const char *text)
{
fprintf(stderr, "DEBUG '%s':%d: %s\n");
}
As MCVE test-log-debug.c
:
#include <stdio.h>
#define LOG_DEBUG(TEXT) log_debug(__FILE__, __LINE__, TEXT)
void log_debug(const char *file, int line, const char *text)
{
fprintf(stderr, "DEBUG '%s':%d: %s\n", file, line, text);
}
/* test/sample */
int main()
{
LOG_DEBUG("in main()");
return 0;
}
Compiled and tested with gcc
in cygwin on Windows 10 (64 bit):
$ gcc --version
gcc (GCC) 6.4.0
$ gcc -std=c11 -g -o test-log-debug test-log-debug.c
$ ./test-log-debug
DEBUG 'test-log-debug.c':13: in main()
$
Compiled and tested in VS2013 on Windows 10 again:
DEBUG 'C:\Users\Scheff\tests\test-log-debug.c':13: in main()
visibleman noted that there is a very similar question SO: Visual C++ equivalent of __FILE__ , __LINE__ and __PRETTY_FUNCTION__.
AFAIK, (and also mentioned in one that answers) __FILE__
and __LINE__
are standard. Other/similar macros might be provided as proprietary extension of the compiler.
Upvotes: 2