问题描述
我编写了一个在 linux 上完美运行的 C 程序,但是当我在 Windows 上编译它时,它给我一个错误,说 asprintf() 未定义.它应该是 stdio 库的一部分,但似乎许多编译器不包含它.我可以为 Windows 使用哪个编译器,它允许我使用 asprintf() 函数?我已经尝试了多个编译器,但到目前为止似乎没有一个定义它.
I have written a C program which works perfectly on linux, but when I compile it on windows, it gives me an error saying that asprintf() is undefined. It should be a part of the stdio library but it seems that many compilers do not include it. Which compiler can I use for windows which will allow me to use the asprintf() function? I have tried multiple compilers and none seem to define it so far.
推荐答案
asprintf()
函数不是 C 语言的一部分,并非在所有平台上都可用.Linux 拥有它的事实不寻常.
The asprintf()
function is not part of the C language and it is not available on all platforms. The fact that Linux has it is unusual.
您可以使用 _vscprintf
和 _vsprintf_s
编写自己的代码.
You can write your own using _vscprintf
and _vsprintf_s
.
int vasprintf(char **strp, const char *fmt, va_list ap) {
// _vscprintf tells you how big the buffer needs to be
int len = _vscprintf(fmt, ap);
if (len == -1) {
return -1;
}
size_t size = (size_t)len + 1;
char *str = malloc(size);
if (!str) {
return -1;
}
// _vsprintf_s is the "secure" version of vsprintf
int r = _vsprintf_s(str, len + 1, fmt, ap);
if (r == -1) {
free(str);
return -1;
}
*strp = str;
return r;
}
这是从记忆中得出的,但它应该与您为 Visual Studio 运行时编写 vasprintf
的方式非常接近.
This is from memory but it should be very close to how you would write vasprintf
for the Visual Studio runtime.
_vscprintf
和 _vsprintf_s
的使用是 Microsoft C 运行时独有的奇怪之处,您不会在 Linux 或 OS X 上以这种方式编写代码._s 版本,虽然标准化,但实际上在 Microsoft 生态系统之外并不经常遇到,而且 _vscprintf
甚至在其他地方都不存在.
The use of _vscprintf
and _vsprintf_s
are oddities unique to the Microsoft C runtime, you wouldn't write the code this way on Linux or OS X. The _s
versions in particular, while standardized, in practice are not often encountered outside the Microsoft ecosystem, and _vscprintf
doesn't even exist elsewhere.
当然,asprintf
只是对 vasprintf
的包装:
Of course, asprintf
is just a wrapper around vasprintf
:
int asprintf(char **strp, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int r = vasprintf(strp, fmt, ap);
va_end(ap);
return r;
}
这不是编写 asprintf
的可移植"方式,但如果您的唯一目标是支持 Linux + Darwin + Windows,那么这是最好的方式.
This is not a "portable" way to write asprintf
, but if your only goal is to support Linux + Darwin + Windows, then this is the best way to do that.
这篇关于在 Windows 上使用 asprintf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!