c++cextern-c

Problem with using C code in C++ with extern "C"


I know when i want to link C code as C code in C++ should i use extern "C". But with the following code :

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

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

I get this compile time error:

C4430: missing type specifier - int assumed. Note: C++ does not support defualt-int.

How i can deal with this ?
I use MSVC2017 on MS-Windows10.

EDIT: I know that most declare the function with a explicit return type, But i what to use USBPcap and USBPcap declare some function like that. How i can use it in my own C++ program ?


Solution

  • extern "C" only changes the linkage of declarations. In particular, it disables C++ name mangling that is otherwise needed for some C++ features such as overloading.

    extern "C" does not make the enclosed part of the program to be compiled as C. As such, the declarations must still be well-formed C++. some (void) is not a well-formed declaration in C++, which explains the error.

    How i can deal with this ?

    Declare the return type explicitly.

    USBPcap declare some function like that. How i can use it in my own C++ program ?

    Then you cannot use that header. You can write a C++ compatible header yourself. Or, you can use a C++ compiler that supports impilict int as an extension.

    P. S. Implicit int is not well-formed in C language either since C99.