【问题标题】:If I declare a function with extern "C", should I also define it that way?如果我用 extern \"C\" 声明一个函数,我是否也应该这样定义它?
【发布时间】:2022-10-14 22:35:18
【问题描述】:

在我的头文件foo.h 中,我有:

#ifdef __cplusplus
extern "C" {
#endif

int foo(int x); 

#ifdef __cplusplus
}
#endif

现在,在foo.cpp 中,我是否也应该使用extern "C",并定义:

#include "foo.h"

extern "C" { 
int foo(int x); 
};

?或者声明是否足以确保 C 链接(没有名称修改)?

【问题讨论】:

    标签: c++ header forward-declaration function-declaration extern-c


    【解决方案1】:

    extern "C" 标记声明就足够了。

    如果包含函数声明的翻译单元带有extern "C",编译器将在最终遇到实现时尊重这一点 - 并在目标文件中使用未损坏的符号。

    请参阅GodBolt

    但请记住,如果您的实现确实不是看看你的标题,如果你不明确这样做,没有什么可以使它成为外部“C”。

    【讨论】:

    • 编译器将在目标文件中放置一个 C 错误符号。这通常是源代码中的名称,前面带有下划线。
    【解决方案2】:

    它会尊重第一个声明

    除了具有 C++ 链接的函数外,没有链接规范的函数声明不得在该函数的第一个链接规范之前。

    在看到显式链接规范后,可以在没有链接规范的情况下声明函数;先前声明中明确指定的链接不受此类函数声明的影响。

    §dcl.link

    extern "C" int C1();
    extern "C" int C1() { return 1; } // ok, C linkage, same as previous declaration
    
    extern "C" int C2();
    int C2() { return 1; } // ok, C linkage, preserve previous
    
    int C3();
    extern "C" int C3();   // error, only C++ linkage can specified after first declaration
    
    
    int F0();
    int F0() { return 1; } // ok, C++ linkage by default
    
    extern "C++" int F1();
    extern "C++" int F1() { return 1; } // ok, C++ linkage
    
    extern "C++" int F2();
    int F2() { return 1; } // ok, C++ linkage
    
    int F3();
    extern "C++" int F3(); // ok, C++ linkage can specified after first declaration
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多