【问题标题】:Does extern "C" have any effect in C?extern "C" 在 C 中是否有任何影响?
【发布时间】:2009-04-04 20:12:32
【问题描述】:

我刚刚得到一些使用 extern "C" 来声明外部函数的 C 代码,如下所示:

extern "C" void func();

这是有效的 C 吗?我在这一行遇到错误,但我不确定是因为这个还是其他原因。

【问题讨论】:

    标签: c++ c extern-c


    【解决方案1】:

    不,它不是有效的 C。它只能在 C++ 代码中用于引用 C 代码中定义的函数。 extern "C" 应该被 ifdef __cplusplus/#endif 块包围:

    // For one function
    #ifdef __cplusplus
    extern "C"
    #endif
    void func();
    
    // For more than one function
    #ifdef __cplusplus
    extern "C"
    {
    #endif
    
    void func1();
    void func2();
    
    #ifdef __cplusplus
    }
    #endif
    

    【讨论】:

      【解决方案2】:

      这是一种 C++ 表示法,用于告诉编译器/链接器使用 C 调用标准。

      通常该行包含在预处理器语句中。

      #ifdef __cplusplus
      extern "C" {
      #endif
      
      // stuff
      
      #ifdef __cplusplus
      }
      #endif
      

      【讨论】:

        【解决方案3】:

        在 C 中无效。如果在预处理后出现,这将导致按照标准进行诊断。

        对于 C++,这变成了名称修改。请参阅this 了解有关为什么需要它的更多详细信息。你能发布更多细节吗?

        【讨论】:

          猜你喜欢
          • 2019-12-22
          • 2010-10-25
          • 2018-11-07
          • 1970-01-01
          • 1970-01-01
          • 2011-07-03
          相关资源
          最近更新 更多