use a C function from a C++ program
-
I have included a c program (driver.lib) which is used as a library for my c++ program (myProgram.exe). from my c++ program I need to call C functions from driver.lib. I keep getting this compiler error: LNK2001: unresolved external symbol I read from the MSDN that I have to use 'extern' to call C functions from a C++ program. My question is how and where to use it. A sample code would be wonderful. thanks in advance ;)
-
I have included a c program (driver.lib) which is used as a library for my c++ program (myProgram.exe). from my c++ program I need to call C functions from driver.lib. I keep getting this compiler error: LNK2001: unresolved external symbol I read from the MSDN that I have to use 'extern' to call C functions from a C++ program. My question is how and where to use it. A sample code would be wonderful. thanks in advance ;)
In your header file containing the C functions
#ifdef __cplusplus
extern "C"
{
#endif//define your C functions here
void cFunction(int arg1)
{
...
}#ifdef __cplusplus
}
#endifStephen Kellett -- C++/Java/Win NT/Unix variants Memory leaks/corruptions/performance/system problems. UK based. Problems with RSI/WRULD? Contact me for advice.
-
I have included a c program (driver.lib) which is used as a library for my c++ program (myProgram.exe). from my c++ program I need to call C functions from driver.lib. I keep getting this compiler error: LNK2001: unresolved external symbol I read from the MSDN that I have to use 'extern' to call C functions from a C++ program. My question is how and where to use it. A sample code would be wonderful. thanks in advance ;)
To use a 'C' libary in a 'C++' program, in the header file for the c program, you prefix function declarations with "extern C" preprocessor commands. For example, if you are using only C++, just do this in driver.h: extern "C" void ExportedFunction(void* pBlah); This tells the C++ complier that this function is to be treated as a plain ole 'C' function. If you have several exported functions in the header file, you don't have write "extern C" for each one, you can use braces: extern "C" { char ShowChar( char ch ); char GetChar( void ); } If driver.h might also be used by a 'C' compiler, you use the processor to make sure that only the C++ compiler sees the "extern" command: #ifdef __cplusplus extern "C" { #endif void ExportedCfunction1(void *pBlah); void ExportedCfunction2(void *pBlah); void ExportedCfunction3(void *pBlah); #ifdef __cplusplus } #endif If you don't want to change driver.h, you can surround the include statement in the cpp file for the driver with the extern command: // Cause everything in the header file "cinclude.h" // to have C linkage. extern "C" { #include //from MSDN } See "Linkage to Non-C++ Functions" in MSDN for more fun with "extern". Of course you want to be sure that the linker knows where to find driver.lib. In Visual Studio you do this with the project settings->linker. Jim