知道程序执行的确切行
Know exact line of the program execution
我正在尝试为我的程序做一个调试模式,在一个文件中写入类似这样的东西来存储日志:
[Day Month D HH:MM:SS YYYY] foo.c function_name line 33: The thing
that happens
问题是知道线的确切值,显然我可以在我的IDE中看到它,但我想知道是否存在更优雅和有效的方式。
我希望你已经很好地解释了我(如果没有,请见谅)并提前致谢。
您可以查看宏 assert
(assert.h
),它是按照您的预期完成的。
简而言之:
必须是宏。如果它是一个函数,它会报告这个函数的文件和行,但实际上你会想要调用函数的文件和行。 (这并不意味着该宏不能调用辅助函数。)
宏__FILE__
和__LINE__
.
可以访问当前文件和行
它在源代码中是这样的:
#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");
}
作为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;
}
在 Windows 10(64 位)上用 gcc
在 cygwin 中编译和测试:
$ 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()
$
在 Windows 10 上再次在 VS2013 中编译和测试:
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,(并且在回答中也提到)__FILE__
和 __LINE__
是标准的。 Other/similar 宏可能作为编译器的专有扩展提供。
我正在尝试为我的程序做一个调试模式,在一个文件中写入类似这样的东西来存储日志:
[Day Month D HH:MM:SS YYYY] foo.c function_name line 33: The thing that happens
问题是知道线的确切值,显然我可以在我的IDE中看到它,但我想知道是否存在更优雅和有效的方式。
我希望你已经很好地解释了我(如果没有,请见谅)并提前致谢。
您可以查看宏 assert
(assert.h
),它是按照您的预期完成的。
简而言之:
必须是宏。如果它是一个函数,它会报告这个函数的文件和行,但实际上你会想要调用函数的文件和行。 (这并不意味着该宏不能调用辅助函数。)
宏
__FILE__
和__LINE__
. 可以访问当前文件和行
它在源代码中是这样的:
#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");
}
作为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;
}
在 Windows 10(64 位)上用 gcc
在 cygwin 中编译和测试:
$ 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()
$
在 Windows 10 上再次在 VS2013 中编译和测试:
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,(并且在回答中也提到)__FILE__
和 __LINE__
是标准的。 Other/similar 宏可能作为编译器的专有扩展提供。