Header:
using namespace std;
extern "C" {
string testFunc();
}
.cpp:
string testFunc()
{
return string("test");
}
I got this warning when building:
'testFunc' has C-linkage specified, but returns user-defined type 'string' (aka 'basic_string<char>') which is incompatible with C
I've test my function and "test" was returned properly.
Will this warning cause any issue?
I'm using Apple LLVM 4.2, C99, ALL default settings in XCode 4.6.
Presumably you are wrapping the declaration of testFunc
in extern "C"
because you want to be able to call it from a C program. However, when a C program calls this function, they're going to get a std::string
back, which is completely incompatible with C. The program will just have no way to manage it.
Either testFunc
shouldn't be inside extern "C"
or it should be returning the string in a C-style way (perhaps as a const char*
).
For a class type to be compatible with C, it should be a standard-layout class (in C++11 terminology).
A standard-layout class is a class that:
- has no non-static data members of type non-standard-layout class (or array of such types) or reference,
- has no virtual functions (10.3) and no virtual base classes (10.1),
- has the same access control (Clause 11) for all non-static data members,
- has no non-standard-layout base classes,
- either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
- has no base classes of the same type as the first non-static data member.
It should also not have its name mangled, which occurs when the type is in a namespace or when it is a template type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With