Link to home
Start Free TrialLog in
Avatar of woigl
woigl

asked on

C App with C++ Lib

i wrote a library in C++ and compiled with VC6.0

now i write a C program in VC6.0 and want to link the C++ lib to it.

but i get always undefined references at linking time... if i change my app to C++ then it works...

can someone tell me and help me to solve the problem?
Avatar of AlexFM
AlexFM

If C++ library exports functions, the problem is in C++ names mangling. Use extern "C" in function definitions to prevent this.
If C++ library exports classes, you need to write C+ wrapper library which translates C++ interface to API interface.
Avatar of woigl

ASKER

I think you got me wrong.

Extern "C" i have to use in case if i want to use a C-function in C++, but i am doing it in the opposite way...

ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The reason you can't link to the external methods is because they're mangled, as everyone else has mentioned. The only way to do it is to change your library to allow C access. You can retain the C++ character of the lib, and simply add extra functions that are flagged as extern "C". These C functions would then access the C++ functionality, allowing you to have a DLL that's both C and C++.
Hi woigl,

I assume you have guessed that you wont be able to access classes and objects etc.

Write a simple interface module for the library. Call it xxx.c (not .cpp) and it should compile usin C standard syntax.

In xxx.c, write a function that invokes each C++ function you want access to in C.

e.g.

Say in module aaa.cpp you have:

 In your xxx.c use:

char * CFunction ( char * string )
{
 return (CPlusPlusFunction ( string ));
}

Paul
extern "C" works both ways. I've done that several times.
You need to make sure that the .h file is perfectly legal in C and doesn't contain anything C++ (that is only for the .h file, of-course, the .cpp file can include any C++ code). Just try #include-ing it from a .c file and check if it causes any compilation errors (Press Ctrl+F7 to compile the current file only).
Then you simply add the following to the beginning of the .h file:
#ifdef __cplusplus
extern "C" {
#endif
and in the end of the file:
#ifdef __cplusplus
}
#endif
It should compile and work perfectly.