【问题标题】:How can I implement a function, which is specified with an "extern" clause in a C header, within a C++ class?如何在 C++ 类中实现在 C 标头中使用“extern”子句指定的函数?
【发布时间】:2020-12-16 21:57:54
【问题描述】:

我将在我用 C++ 编写的项目中使用用 C 实现的驱动程序库。库的header file 包含一些function stubs declared as extern 我将不得不实现:

extern uint8_t ADS1x1x_i2c_start_write (uint8_t i2c_address);

我的 C++ 代码现在包含一个名为 vfd 的类,其中将包含实现各个函数存根的静态方法,如下所示:

uint8_t vfd::ADS1x1x_i2c_start_write (uint8_t i2c_address) {
  uint8_t ret = 0x00;
  // do something
  return ret;
}

vfd类的头文件中,对应的行会是这样的:

class vfd {
  public:
    uint8_t ADS1x1x_i2c_start_write (uint8_t i2c_address);
}

我应该如何声明我的方法,以便编译器将它们识别为我的库头文件中各个 extern 函数的实现?

【问题讨论】:

    标签: c++ static-methods extern


    【解决方案1】:

    我应该如何声明我的方法,以便编译器将它们识别为我的库头文件中各个外部函数的实现?

    你不能那样做。 extern "C" 与类的static 成员函数不同。

    您可以实现extern "C" 函数,使其成为类的static 成员函数的传递。

    extern "C" uint8_t ADS1x1x_i2c_start_write (uint8_t i2c_address)
    {
        return vfd::ADS1x1x_i2c_start_write(i2c_address);
    }
    

    【讨论】:

      【解决方案2】:

      你不能。您可以在您的 C++ 文件中分别实现这些 C 函数,并让它们在类中调用您的静态函数:

      extern "C" uint8_t ADS1x1x_i2c_start_write (uint8_t i2c_address) {
          vfd::ADS1x1x_i2c_start_write(address);
      }
      

      它们是静态的,对吗?否则,您还必须提供一个this 对象来调用该方法,并且它在C API 中没有,您必须自己弄清楚,例如:

      extern "C" uint8_t ADS1x1x_i2c_start_write (uint8_t i2c_address) {
          some_var_of_type_vfd.ADS1x1x_i2c_start_write(address);
      }
      

      【讨论】:

      • 我是否也必须在头文件vfd.h 中引用这些外部“C”函数?
      猜你喜欢
      • 2021-07-15
      • 2017-05-27
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      相关资源
      最近更新 更多