繁体   English   中英

在带有外部“C”的 C++ 中使用 C 代码时出现问题

[英]Problem with using C code in C++ with extern “C”

我知道当我想在 C++ 中将 C 代码链接为 C 代码时,我应该使用extern "C" 但是使用以下代码:

/* file.h */
some (void)
{
    return 10;
}
extern "C"
{
    #include "file.h"
}
#include <iostream>

int main (void)
{
    std::cout << some() << std::endl;
}

我得到这个编译时错误:

C4430:缺少类型说明符 - 假定为 int。 注意:C++ 不支持默认整数。

我该如何处理?
我在MS-Windows10上使用MSVC2017

编辑:我知道大多数声明 function 具有显式返回类型,但我使用USBPcap和 USBPcap 声明一些 function 之类的。 我如何在我自己的 C++ 程序中使用它?

所有函数都应指定返回类型。 您没有为some指定一个。

在旧版本的 C 中,如果省略 function 的返回类型,则默认为int C++ 但是不支持。

您应该始终指定函数的返回类型:

int some(void)
{
    return 10;
}

extern "C"仅更改声明的链接。 特别是,它禁用了 C++ 功能(例如重载)需要的 C++ 名称修改。

extern "C"不会使程序的封闭部分编译为 C。 因此,声明仍然必须是格式良好的 C++。 some (void)不是 C++ 中格式正确的声明,它解释了错误。

我该如何处理?

显式声明返回类型。

USBPcap 像这样声明一些 function。 我如何在我自己的 C++ 程序中使用它?

那么你不能使用那个 header。 你可以自己写一个C++兼容header。 或者,您可以使用支持隐式 int 作为扩展的 C++ 编译器。

PS 隐式 int 从 C99 开始在 C 语言中也不是格式正确的。

  1. 除了 static 内联函数之外,不要将任何代码放入 .h 文件
  2. 其次正确地声明函数 - 而不是懒惰的方式。 什么是some(void) 如果 C++ 编译器知道 function 的返回类型......
    extern "C"
    {
        int some (void)
        {
            return 10;
        }
    }
    #include <iostream>

    int main (void)
    {
        std::cout << some() << std::endl;
    }

https://godbolt.org/z/_AJgFX

编译器已经告诉你到底是什么问题。 您尝试从std::cout调用的 function 需要明确定义返回类型。 In C the compiler automatically set the return type of an undefined-type function to int and you can compile a code that contain untyped function with nothing more of a warning from the compiler, but not do it, it is extremely wrong way to write code . 在 C++ 中,就像编译器告诉你的那样,你不能,所以这是一个错误。 C 和 C++ 中的定义必须有一个 type ,如果你想要一个不返回任何东西的 function ,你需要定义它void 但是,在 c++ 标准的最新版本中,您可以使用auto关键字在编译时自动检测声明的类型,因此如果您希望编译器自动检测某物的类型,请使用它,但要谨慎使用. 所以,最后,如果你想写 C 或 C++ 代码,请在你的定义中添加一个类型,这不是 Z23EEEB4347BDD26BFC6B7EE9A3B755DDEDE2911ZDE9B9ED780DEF7...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM