简体   繁体   English

在 C90 中使用 snprintf

[英]Using snprintf with C90

Is there a way instruct the the compiler that:有没有办法指示编译器:

  • The language is C90语言是C90
  • The declarations of stdio.h are those of C99 (including snprintf) stdio.h 的声明是 C99 的声明(包括 snprintf)

With cc -std=c90 -Wall (on a source file using snprintf), an annoying warning is issued (sometimes, depending on the compiler/environment, with a confusing hint that stdio.h should be included, even if it already is), but the linker finds snprintf anyway.使用cc -std=c90 -Wall (在使用 snprintf 的源文件上),会发出令人讨厌的警告(有时,取决于编译器/环境,带有令人困惑的提示,即应包含 stdio.h,即使它已经包含) ,但链接器无论如何都会找到 snprintf 。 I understand what is happening, that is not the question.我明白发生了什么,这不是问题。

Using strict c90 (language) and snprintf (library function) is technically well possible, but I do not know how to instruct the compiler accordingly.使用严格的 c90(语言)和 snprintf(库函数)在技术上是可行的,但我不知道如何相应地指示编译器。 In other words, I would like to distinguish between language compliance and library compliance.换句话说,我想区分语言合规性和合规性。

Remark: I assume that the language used in the C99 stdio.h header file is actually C90, and that it could thus be included by a C90 source file.备注:我假设 C99 stdio.h 头文件中使用的语言实际上是 C90,因此它可以包含在 C90 源文件中。 Does anything prevent it?有什么可以阻止它吗?

I would prefer a solution with a generic include <stdio.h> , for the sake of portability.为了可移植性,我更喜欢带有通用include <stdio.h>的解决方案。

No.不。

A generic #include <stdio.h> for a C90 compiler needs not declare snprintf . C90 编译器的通用#include <stdio.h>不需要声明snprintf

Before you argue that it's not a C90 compiler, keep in mind that you are requesting that it acts as one usng -std=c90 .在您争辩说它不是 C90 编译器之前,请记住您要求它充当一个 usng -std=c90 A compiler acting as a C90 compiler needs not do anything that a C90 compiler wouldn't do.作为 C90 编译器的编译器不需要做任何 C90 编译器不会做的事情。

There is therefore no generic solution.因此没有通用的解决方案。

There may be compiler-specific solutions, including adding the following:可能有特定于编译器的解决方案,包括添加以下内容:

int snprintf( char * buffer, size_t bufsz,  const char * format, ... );

Yes, though it's a bit of a weird thing to do.是的,虽然这样做有点奇怪。

You can define _ISOC99_SOURCE to signal that you want C99 functions to be defined.您可以定义_ISOC99_SOURCE来表示您希望定义 C99 函数。

Example:例子:

#define _ISOC99_SOURCE
#include <features.h>
#include <stdio.h>

int main() {
    char buf[10];
    snprintf(buf, 4, "foo");
    puts(buf);
    return 0;
}

Compile it like so:像这样编译它:

$ gcc -std=c90 -Wall test.c  
$ ./a.out 
foo

This will work in gcc 10.3.0 and clang 11.0.0.这将适用于 gcc 10.3.0 和 clang 11.0.0。 In terms of library compatibility, it has only been tested with glibc, and not musl or other versions of the standard library.在库兼容性方面,只用glibc测试过,没有用musl或其他版本的标准库测试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM