【问题标题】:Consistency between a function's declaration in a C header and its definition in a .cpp fileC 标头中的函数声明与其在 .cpp 文件中的定义之间的一致性
【发布时间】:2014-07-30 14:30:25
【问题描述】:

考虑一个 C++ 函数,我想在 C 中接口它(例如,int foo()),它不接受输入参数。

C 中缺少输入参数可以表示为int foo(void);,而C 中的int foo() 表示任意数量的输入参数。

但是,在 C++ 中,int foo() 表示不带参数的函数,int foo(void) 被视为应避免的 C 向后兼容残余。

考虑到上述情况,什么是最合适的?

选项 1:

C 头声明:int foo(void);

C++ 文件定义:int foo(void) { ... }

选项 2:

C 头声明:int foo();

C++ 文件定义:int foo() { ... }

选项 3:

C 头声明:int foo(void);

C++ 文件定义:int foo() { ... }

【问题讨论】:

    标签: c++ c void


    【解决方案1】:

    好的,我们已经知道 C 和 C++ 中 f() and f(void) 之间的区别。

    由于在 C 中使用 f() 是不好的做法(您失去了编译器将函数的声明与其定义进行比较以确保正确调用它的能力)并且您具有该函数的 C 链接,我建议使用f(void)

    毕竟,在 c++ 中,f(void) 只是为了与 C 向后兼容而保持活力,这正是您的用例。


    只是一个小更正:输入参数的数量不是任意数量,而是未指定,这意味着可变参数函数存在严重差异。

    【讨论】:

      【解决方案2】:

      我会使用:

      // Header
      #ifdef __cplusplus
      extern "C" {
      #endif
      void foo(void);
      #ifdef __cplusplus
      }
      #endif
      

      对于 cpp 文件:

      // in cpp file
      extern "C" {
          void foo(void)
          {
              // implementation
          }
      }
      

      正如我们明确表明我们使用 C。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-11
        • 1970-01-01
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        • 2018-11-09
        相关资源
        最近更新 更多