gpt4 book ai didi

c++ - 从 C++ 链接到 C 库 : why isn't extern always needed?

转载 作者:太空狗 更新时间:2023-10-29 20:33:32 25 4
gpt4 key购买 nike

通常要从 C++ 获得一个 C 库,你必须将它包含在 extern "C" { #include <clibrary.h> } 中。 .许多库将在其头文件中包含类似 #ifdef __cplusplus extern "C" { ... 的代码。使它们对 C++ 代码更友好(例如 pthread.h )。有时情况并非如此。例如,stdio.h没有这样的#ifdef ,但我仍然可以编译和链接通常的 #include <stdio.h> int main() {printf("Hello");}使用 C++ 编译器而不将其包装在 extern "C" 中陈述。为什么是这样?

最佳答案

Usually to get a C library working from C++ you have to include it with extern "C" { #include <clibrary.h> }.

仅当库在设计时没有考虑到 C++ 兼容性。但这是一个 hack。

Many libraries will include in their header files code like #ifdef __cplusplus extern "C" { ... to make them more user friendly to C++ code (e.g. pthread.h)

是的,一个好的图书馆会做到这一点。

因此,您不需要也不应该添加另一个 extern "C" #include周围.

stdio.h是将正确执行此操作的 header 示例(见下文)。

For instance, stdio.h has no such #ifdef

当然可以! Follow the money trail

why isn't extern always needed?

所以,总而言之,当头文件的作者没有为你做的时候,你只需要自己做。头文件的作者做了,你就不用做了。

关于c++ - 从 C++ 链接到 C 库 : why isn't extern always needed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54440260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com