使用 C++ 编译的 C 代码:未定义的引用

发布于 2024-09-01 09:50:07 字数 271 浏览 2 评论 0原文

我有一个小程序,可以毫无困难地使用 GCC 和 ICC 进行编译,但我也希望代码能够使用 G++ 和 ICPC。 添加 this:

#ifdef __cplusplus
  extern "C" {
#endif

我尝试在所有头文件的开头

#ifdef __cplusplus
  }
#endif

,在所有头文件的末尾添加 this: ,但我仍然收到几个“对“...”的未定义引用”错误。

I have a small program that I can compile with GCC and ICC without any difficulties, but I would also like the code to work with G++ and ICPC. I tried to add this:

#ifdef __cplusplus
  extern "C" {
#endif

at the beginning and this:

#ifdef __cplusplus
  }
#endif

at the end of all the header files, but I still get several `undefined reference to "..."' errors.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

花开半夏魅人心 2024-09-08 09:50:07

我认为你弄错了...... extern C 用于禁用函数修饰;因此,如果您仅对头文件执行此操作,则当您尝试链接损坏的目标代码时,声明的函数名称将与目标文件中的函数名称不匹配。

无论如何,如果整个应用程序使用相同的 C++ 编译器进行编译和链接,extern C 不会增加任何可移植性,它的目的是将 C 库与 C++ 代码混合在一起。

如果您的代码属于 C 和 C++ 的公共子集,那么您应该已经能够使用任一编译器对其进行编译,但我看不出这样做的原因(除了遵循最小惊喜原则之外,因为 C++ 对一些事情)。

I think you're getting it wrong... The extern C is for disabling the function mangling; so if you do it just for the header files, when you try to link your mangled object code, the declared function names won't match with the function names in the object file.

Anyway, the extern C won't add any portability if the whole application is being compiled and linked with the same C++ compiler, it's intended for mixing C libraries with C++ code.

If your code is in the common subset of C and C++, you should be already able to compile it with either compiler, but I cannot see the reason to do that (besides working on the principle of least surprise, as C++ is more strict with some things).

淡忘如思 2024-09-08 09:50:07

您会得到未定义的引用,因为如果您放置 extern "C",则声明和定义不匹配,这会防止发生名称修改:但在这种情况下,这种情况仅发生在您的头文件中。

You get undefined references because the declaration and the definition are not matching if you put extern "C", which prevents name mangling from happening: but in this case this is happening only in your header files.

稀香 2024-09-08 09:50:07

如果未定义的引用之一是 gxx_personality,那么我会说“fortran”的帖子是正确的。

If one of the undefined references is gxx_personality, then I'd say the post by "fortran" is correct.

一杆小烟枪 2024-09-08 09:50:07

请参阅我对这个早期问题的回答: 何时使用 extern "C"简单的话?

它应该能够清楚地说明如何混合 C 和 C++ 代码。

See my response to this earlier question: When to use extern "C" in simple words?

It should hopefully make it clear how to mix C and C++ code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文