jmckay321
asked on
Calling C routine from C++
I am trying to integrate the RSA MD5 hash code, written in C, into my C++ project (Visual C++ 2008 Express). The project has a separate file with the MD5 code, and compiles fine. However I get a link error when I try to call it from my C++ code. The link error is:
error LNK2019: unresolved external symbol "void __cdecl MD5Init(struct MD5Context *)" (?MD5Init@@YAXPAUMD5Contex t@@@Z) referenced in function _com_GetHash
(actually there are 3 routines that fail to link, this is just one)
I assume the problem is related to how I have the routines defined, but nothing I try seems to fix it. The routine referenced above is defined in the header file (included in both the C and C++ modules) as:
extern void MD5Init(struct MD5Context *);
Any ideas?
error LNK2019: unresolved external symbol "void __cdecl MD5Init(struct MD5Context *)" (?MD5Init@@YAXPAUMD5Contex
(actually there are 3 routines that fail to link, this is just one)
I assume the problem is related to how I have the routines defined, but nothing I try seems to fix it. The routine referenced above is defined in the header file (included in both the C and C++ modules) as:
extern void MD5Init(struct MD5Context *);
Any ideas?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I check the Microsoft docs for predefined macros and __cplusplus is correct.
Here is a good explanation of name mangling in c++:
http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_C.2B.2B
http://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_C.2B.2B
>> check the Microsoft docs for predefined macros and __cplusplus is correct
Actually, no need to check, since it is defined in the C++ standard:
16.8 Predefined macro names
_ _cplusplus The name _ _cplusplus is defined to the value 199711L when compiling a C + + translation unit
Actually, no need to check, since it is defined in the C++ standard:
16.8 Predefined macro names
_ _cplusplus The name _ _cplusplus is defined to the value 199711L when compiling a C + + translation unit
So, using __cplusplus is good for any compiler/liner that is compliant to the ISO/IEC 14882 C++ standard.
ASKER
Thank you all for your comments - I do recall the issue now, needed a refresher course...
extern "C" void MD5Init(struct MD5Context *);
You can also try to make the C routine a C++ routine by changing the file extension from .c to .cpp. But then there may be compiler errors/warnings that you may have to deal with. If not too many, that is a good way to go as well (but now you have to thoroughly retest the new .cpp module).