c++ - 在 C++ 中使用 C 库时遇到问题

标签 c++ c shared-libraries

为了自学一点 C++,我决定编写一个小程序来将文本写入我的 Saitek X52 Pro 操纵杆显示屏。

我想使用 Eduards C 库 http://plasma.hasenleithner.at/x52pro/

我知道如果我想在我的 C++ 程序中使用这些方法,我必须在这些方法周围放置一个“extern C”。但这意味着更改库的头文件 - 然后它就不会再构建了。 在这种情况下,正确的方法是什么?

编辑:建议的方法部分有效。

通讯.cpp:

...
extern "C"{
#include <x52pro.h>
}
using namespace std;
int main ( int argc, char *argv[] ) {
    cout<<"entered main"<<endl;
    char *String;
    strcpy(String,"testing");
    struct x52 *hdl = x52_init();
    x52_settext(hdl, 0,String , 7);
    x52_close(hdl);
    return EXIT_SUCCESS;
}

错误消息:

Comm.o: In function `main': 
Comm.cpp|38| undefined reference to `x52_init' 
Comm.cpp|39| undefined reference to `x52_settext' 
Comm.cpp|40| undefined reference to `x52_close'

这些都是x52pro.h中定义的方法

最佳答案

要在 C 头文件中使用 extern "C",请将其包装起来

#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif

或者您可以使用 extern "C" 包装 #include

extern "C" {
#include <chdr1.h>
#include <chdr2.h>
}

链接应用程序时,必须告诉链接器要使用哪个库以及该库在哪里。从您的链接中,您还必须添加 libusb。看起来大致是这样的

g++ -o app_name Comm.o -L /path/to/library -lx52pro -lusb

当库安装在系统lib目录下时,可以省略-L/path/...部分。如果您使用 Makefile,您可以在一些变量中定义它,通常是

LDFLAGS = -L /path/to/library
LDLIBS = -lx52pro -lusb

另请参阅Compiling and LinkingWikipedia - Linker (computing)

关于c++ - 在 C++ 中使用 C 库时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408757/

相关文章:

c++ - 无法使用 clang_complete 完成 qt

c++ - 返回模板化的依赖类型

c - CentOS 和 Windows 之间关于端口号的不同行为

java - 在 Jetty Web 服务器中管理共享库

c++ - QMetaObject::connectSlotsByName:没有匹配的信号

c++ - 3点的平面方程式未返回正确值

C拼图: Make a fair coin from a biased coin

c - 在C二叉树中插入函数?

c - 如何从 FILE* 写入 fd?

shared-libraries - 如何使用 pkglib_LTLIBRARIES = test.la 只构建 *.so