为什么使用 fprintf 的内联函数需要声明为静态的?

Why does inline function need to be declared static if it uses fprintf?

我正在重构一些 C 代码并对分解出的部分执行单元测试(使用 Google 测试)。一个片段在一个循环中被多次使用,所以为了将它暴露给测试,我将它分解为 header 文件 demo.h 中的 inline 函数,其中还包括一些其他的声明非 inline 函数。简化版如下:

#ifndef DEMO_H_
#define DEMO_H_
#ifdef __cplusplus
extern "C" {
#endif
inline void print_line(FILE* dest, const double * data, int length) {
    for (int s = 0; s < length; s++)
        fprintf(dest, "%lf ", data[s]);
    fprintf(dest, "\n");
}
#ifdef __cplusplus
}
#endif
#endif /* MK_H_ */

我的测试代码

#include "gtest/gtest.h"
#include "demo.h"
#include <memory>
#include <array>
#include <fstream>

TEST (demo, print_line) {
    std::array<double,4> test_data = {0.1, 1.4, -0.05, 3.612};

    const char* testfile = "print_line_test.txt";
    {
        auto output_file = std::unique_ptr<FILE, decltype(fclose)*>{
            fopen(testfile, "w"), fclose };
        print_line(output_file.get(), test_data.data(), test_data.size());
    }

    std::ifstream input(testfile);
    double dval;
    for(const auto& v: subsequence_data) {
        input >> dval;
        EXPECT_EQ (v, dval);
    }
    EXPECT_FALSE (input >> dval) << "No further data";
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

此代码在带有 -std=gnu++0x 的 MinGW g++ 4.8.1 下编译和运行良好。

原来的C代码就是利用了这个函数。简化版本如下:

#include "demo.h"

void process_data(const char* fname, double ** lines, int num_lines, int line_length) {
    FILE* output_file = fopen(fname, "w");
    for (int i=0; i<num_lines; ++i) {
      print_line(output_file, lines[i], line_length);
    }
}

但是,当我尝试使用带有 -std=c99 的 MinGW GCC 4.8.1 编译我的 C 代码时,我收到以下警告:

warning: 'fprintf' is static but used in inline function 'print_line' which is not static [enabled by default]

我也得到一个后续的错误,可能是相关的:

undefined reference to `print_line'

将 header 中的签名更改为 static inline void print_line ... 似乎可以解决问题。但是,我不喜欢不了解问题的原因。为什么缺少 static 不影响 C++ 测试?关于 fprintf 的错误实际上意味着什么?

首先,inline 的行为在 C 和 C++ 中是不同的,特别是在所涉及符号的链接方面。 (并且在 ISO C 和 GNU C 之间也有所不同)。

您可以阅读有关 C 版本的信息 here

如果您尝试将函数 body 放入 C 和 C++(在同一项目中)都包含的 header 中,那么您将打开一个真正的蠕虫罐头。两种语言标准均未涵盖这种情况。实际上,我会将其视为 ODR violation,因为该函数的 C 版本与 C++ 版本不同。

安全的做法是只在 header 中包含函数原型,并在 non-header 源文件之一中包含函数 body。

如果没有 static,您将允许 C99 编译器创建具有外部链接的函数(在一个地方定义),而且还会在包含该文件的每个翻译单元中创建单独的内联代码。它可以使用它喜欢的任何函数,除非您在 staticextern.

之间明确决定

C99 Draft 6.7.4.3:

中可以看到此类功能的一个要求

An inline definition of a function with external linkage shall not contain a definition of a modifiable object with static storage duration, and shall not contain a reference to an identifier with internal linkage.

这是有道理的,因为编译器希望这个函数具有相同的行为,无论它选择如何实现它。

因此,在这种情况下,编译器抱怨您的 non-static 内联函数正在调用一个不同的函数,即 static,并且不确定另一个函数 (fprintf) 不会改变静态存储。