为了自学一点 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
关于c++ - 在 C++ 中使用 C 库时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408757/