I have a c-library which I use in gcc. The library has the extension .lib but is always linked as a static library. If i write a program which uses the library as c-code, ev
Your library appears to have an API that assumes it will be called from C, not C++. This is important because C++ effectively requires that the symbols exported from a library have more information in them than just the function name. This is handled by "name mangling" the functions.
I assume your library has an include file that declares its public interface. To make it compatible with both C and C++, you should arrange to tell a C++ compiler that the functions it declares should be assumed to use C's linkage and naming.
A likely easy answer to test this is to do this:
extern "C" {
#include "customlibrary.h"
}
in your main.cpp instead of just including customlibrary.h
directly.
To make the header itself work in both languages and correctly declare its functions as C-like to C++, put the following near the top of the header file:
#ifdef __cplusplus
extern "C" {
#endif
and the following near the bottom:
#ifdef __cplusplus
}
#endif
Does your header file have the usual
#ifdef __cplusplus
extern "C" {
#endif
// ...
#ifdef __cplusplus
} /* extern "C" */
#endif
to give the library functions C linkage explicitly.
.cpp files are compiled with C++ linkage i.e. name mangling by default.
The C++ compiler performs what is known as name-mangling - the names that appear in your code are not the same ones as your linker sees. The normal way round this is to tell the compiler that certain functions need C linkage:
// myfile.cpp
extern "C" int libfun(); // C function in your library
or do it for a whole header file:
// myfile.cpp
extern "C" {
#include "mylibdefs.h" // defs for your C library functions
}