【发布时间】:2020-01-19 06:16:01
【问题描述】:
我希望能够创建一个日志记录机制,它非常简单地将参数传递给 printf,但我需要语法突出显示和输入验证。这是我目前拥有的Log 命名空间的大纲。
#pragma once
#include "pch.h"
namespace Log
{
// Determines whether to create the console window or not.
// Turn off for before release.
extern bool CreateConsoleWindow;
// Initialisation.
extern bool Init();
// Writes a line to the console, appended with \r\n.
extern void WriteLine(const char* _Format, ...);
// Writes a line to the console, with a [Debug] prepend.
extern void DebugInfo(const char* _Format, ...);
// Writes a line to the console, with a [Server] prepend.
extern void ServerInfo(const char* _Format, ...);
// Destruction.
extern bool Dispose();
}
这是我对Log::WriteLine(_Format, ...) 的实现:
// Writes a line to the console, appended with \r\n.
void WriteLine(const char* _Format, ...)
{
// Print the message.
char buffer[4096];
va_list args;
va_start(args, _Format);
auto rc = vsnprintf(buffer, sizeof(buffer), _Format, args);
va_end(args);
// Append the new line.
printf("\r\n");
}
但是当我这样做时,我会从输入字符串中丢失所有验证和语法突出显示,这对于初学者来说是必不可少的。例如:
auto hash = Crypto::GetHash(syntax[1].c_str()); // unsigned long, by way of multiple nested macros.
printf("Hash: %d", hash);
这会以浅绿色显示%d,并且printf 中的hash 上会出现警告,说它不会显示,因为它需要%lu。我依靠 VS 来教我我做错了什么,这样我就可以从错误中吸取教训。
如果我对我的函数做同样的事情:
auto hash = Crypto::GetHash(syntax[1].c_str()); // unsigned long, by way of multiple nested macros.
Log::WriteLine("Hash: %d", hash);
那么%d和字符串的其余部分一样是棕色的,并且没有验证错误。
这两件事是必不可少的。有什么方法可以使这项工作正常进行吗?在大约十年的 .NET 经验之后,我是 C++ 的新手,而且学习曲线是巨大的。我想我会从基础开始,只是一个简单的日志系统,所以我可以随时以简洁优雅的方式查看正在输出的内容。在 C# 中,这只需几分钟就可以完成,但在 C++ 中,现在是四个小时后,我在 Firefox 的三个窗口中打开了大约 40 个选项卡,而且我还在用头撞每一面砖墙有可能遇到。
我尝试在命名空间内定义一个宏:
#define WriteLine(_Format, ...) printf(_Format, __VA_ARGS__)
但是说它找不到 printf。我试过用_Printf_format_string_装饰:
extern int _cdecl DebugInfo(_Printf_format_string_ const char* _Format, ...);
但这并没有什么区别。我试过__attribute__((format(printf, 1, 2)))
extern void WriteLine(const char* _Format, ...) __attribute__((format(printf, 1, 2)));
但这会引发大量关于期待 {、unexpected identifier 和 expected a declaration 的错误,但没有说明在哪里、为什么或如何。
对于这样一个基本的要求,我对 C++ 的要求是否过高?
【问题讨论】:
标签: c++ printf visual-studio-2019