-
August 22nd, 2012, 09:59 PM
#1
How to use custom "C" library with C++ codes
I came across a very strength situation while experimenting with creating custom libraries. In my custom library header, I just have this line of code: "double BankAccountBal ( ) ;". my implementation for the library is : "double BankAccountBal ( ) {return 1500.25;};" I then tried compiling this library using C code via setting the Compiled As under Property->C/C++ ->Advanced-> Compiled As to : "Compiled as C Code (/TC). The library compiled fine. Then after the library is built, I include the library in my main project (and properly include all the correct paths, the library link, etc., ), and in my main () I have this line of code: std::cout << BankAccountBal() << std::endl; I tried to build, and got this error : error LNK2019: unresolved external symbol "double __cdecl BankAccountBal(void)" (?BankAccountBal@@YANXZ) referenced in function _wmain. Again, I assured you I have set all the correct paths and link variables. But .... if I went back to the library and compiled as C++ codes instead, via setting the Compiled As under Property->C/C++ ->Advanced-> Compiled As to : "Compiled as C++ Code (/TC). Everything worked !
This suggests that if we are to build C libraries to be used by C++ main codes, there are something missing that need to be set, but I don't know what it is. Any help will be greatly appreciated. Thanks.
-
August 22nd, 2012, 10:49 PM
#2
Re: How to use custom "C" library with C++ codes
I suggest reading this set of FAQ answers on How to mix C and C++.
-
August 23rd, 2012, 05:07 AM
#3
Re: How to use custom "C" library with C++ codes
Originally Posted by zz1234
In my custom library header, I just have this line of code: "double BankAccountBal ( ) ;".
This is where you're wrong. C and C++ are different languages. So, the same line is interpreted different been compiled in C unit compared to C++ one. Compiled in C the line declares _BankAccountBal symbol while in C++ it is ?BankAccountBal@@YANXZ. So you need a special trick to make this be compiled identically:
Code:
#ifdef __cplusplus
extern "C" {
#endif
/* here C stuff goes */
#ifdef __cplusplus
}
#endif
Best regards,
Igor
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|