C-library not linking using gcc/g++

时光怂恿深爱的人放手 提交于 2019-11-30 03:04:16

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

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
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!